How can I safely create a nested directory?

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

    Why not use subprocess module if running on a machine that supports command mkdir with -p option ? Works on python 2.7 and python 3.6

    from subprocess import call
    call(['mkdir', '-p', 'path1/path2/path3'])
    

    Should do the trick on most systems.

    In situations where portability doesn't matter (ex, using docker) the solution is a clean 2 lines. You also don't have to add logic to check if directories exist or not. Finally, it is safe to re-run without any side effects

    If you need error handling:

    from subprocess import check_call
    try:
        check_call(['mkdir', '-p', 'path1/path2/path3'])
    except:
        handle...
    

提交回复
热议问题