How can I safely create a nested directory?

前端 未结 27 2679
旧时难觅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: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
    

提交回复
热议问题