How can I safely create a nested directory?

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

    In Python 3.4 you can also use the brand new pathlib module:

    from pathlib import Path
    path = Path("/my/directory/filename.txt")
    try:
        if not path.parent.exists():
            path.parent.mkdir(parents=True)
    except OSError:
        # handle error; you can also catch specific errors like
        # FileExistsError and so on.
    

提交回复
热议问题