How can I safely create a nested directory?

前端 未结 27 2675
旧时难觅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: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().

提交回复
热议问题