How can I safely create a nested directory?

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

    Starting from Python 3.5, pathlib.Path.mkdir has an exist_ok flag:

    from pathlib import Path
    path = Path('/my/directory/filename.txt')
    path.parent.mkdir(parents=True, exist_ok=True) 
    # path.parent ~ os.path.dirname(path)
    

    This recursively creates the directory and does not raise an exception if the directory already exists.

    (just as os.makedirs got an exist_ok flag starting from python 3.2 e.g os.makedirs(path, exist_ok=True))


    Note: when i posted this answer none of the other answers mentioned exist_ok...

提交回复
热议问题