How can I safely create a nested directory?

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

    You can use mkpath

    # Create a directory and any missing ancestor directories. 
    # If the directory already exists, do nothing.
    
    from distutils.dir_util import mkpath
    mkpath("test")    
    

    Note that it will create the ancestor directories as well.

    It works for Python 2 and 3.

提交回复
热议问题