How can I safely create a nested directory?

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

    Using try except and the right error code from errno module gets rid of the race condition and is cross-platform:

    import os
    import errno
    
    def make_sure_path_exists(path):
        try:
            os.makedirs(path)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
    

    In other words, we try to create the directories, but if they already exist we ignore the error. On the other hand, any other error gets reported. For example, if you create dir 'a' beforehand and remove all permissions from it, you will get an OSError raised with errno.EACCES (Permission denied, error 13).

提交回复
热议问题