How can I safely create a nested directory?

前端 未结 27 2611
旧时难觅i
旧时难觅i 2020-11-22 00:07

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

相关标签:
27条回答
  • 2020-11-22 00:32

    I use os.path.exists(), here is a Python 3 script that can be used to check if a directory exists, create one if it does not exist, and delete it if it does exist (if desired).

    It prompts users for input of the directory and can be easily modified.

    0 讨论(0)
  • 2020-11-22 00:36

    In Python3, os.makedirs supports setting exist_ok. The default setting is False, which means an OSError will be raised if the target directory already exists. By setting exist_ok to True, OSError (directory exists) will be ignored and the directory will not be created.

    os.makedirs(path,exist_ok=True)
    

    In Python2, os.makedirs doesn't support setting exist_ok. You can use the approach in heikki-toivonen's answer:

    import os
    import errno
    
    def make_sure_path_exists(path):
        try:
            os.makedirs(path)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
    
    0 讨论(0)
  • 2020-11-22 00:36

    Call the function create_dir() at the entry point of your program/project.

    import os
    
    def create_dir(directory):
        if not os.path.exists(directory):
            print('Creating Directory '+directory)
            os.makedirs(directory)
    
    create_dir('Project directory')
    
    0 讨论(0)
  • 2020-11-22 00:36

    You have to set the full path before creating the directory:

    import os,sys,inspect
    import pathlib
    
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    your_folder = currentdir + "/" + "your_folder"
    
    if not os.path.exists(your_folder):
       pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
    

    This works for me and hopefully, it will works for you as well

    0 讨论(0)
  • 2020-11-22 00:37

    I would personally recommend that you use os.path.isdir() to test instead of os.path.exists().

    >>> os.path.exists('/tmp/dirname')
    True
    >>> os.path.exists('/tmp/dirname/filename.etc')
    True
    >>> os.path.isdir('/tmp/dirname/filename.etc')
    False
    >>> os.path.isdir('/tmp/fakedirname')
    False
    

    If you have:

    >>> dir = raw_input(":: ")
    

    And a foolish user input:

    :: /tmp/dirname/filename.etc
    

    ... You're going to end up with a directory named filename.etc when you pass that argument to os.makedirs() if you test with os.path.exists().

    0 讨论(0)
  • 2020-11-22 00:38

    Try the os.path.exists function

    if not os.path.exists(dir):
        os.mkdir(dir)
    
    0 讨论(0)
提交回复
热议问题