How can I safely create a nested directory?

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

    For a one-liner solution, you can use IPython.utils.path.ensure_dir_exists():

    from IPython.utils.path import ensure_dir_exists
    ensure_dir_exists(dir)
    

    From the documentation: Ensure that a directory exists. If it doesn’t exist, try to create it and protect against a race condition if another process is doing the same.

提交回复
热议问题