How can I safely create a nested directory?

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

    I have put the following down. It's not totally foolproof though.

    import os
    
    dirname = 'create/me'
    
    try:
        os.makedirs(dirname)
    except OSError:
        if os.path.exists(dirname):
            # We are nearly safe
            pass
        else:
            # There was an error on creation, so make sure we know about it
            raise
    

    Now as I say, this is not really foolproof, because we have the possiblity of failing to create the directory, and another process creating it during that period.

提交回复
热议问题