How to run os.mkdir() with -p option in Python?

谁说胖子不能爱 提交于 2019-11-27 17:41:45

问题


I want to run mkdir command as:

mkdir -p directory_name

What's the method to do that in Python?

os.mkdir(directory_name [, -p]) didn't work for me.

回答1:


You can try this:

# top of the file
import os
import errno

# the actual code
try:
    os.makedirs(directory_name)
except OSError as exc: 
    if exc.errno == errno.EEXIST and os.path.isdir(directory_name):
        pass



回答2:


Something like this:

if not os.path.exists(directory_name):
    os.makedirs(directory_name)

UPD: as it is said in a comments you need to check for exception for thread safety

try:
    os.makedirs(directory_name)
except OSError as err:
    if err.errno!=17:
        raise



回答3:


According to the documentation, you can now use this since python 3.2

os.makedirs("/directory/to/make", exist_ok=True)

and it will not throw an error when the directory exists.




回答4:


If you're using pathlib, use Path.mkdir(parents=True, exist_ok=True)

from pathlib import Path

new_directory = Path('./some/nested/directory')
new_directory.mkdir(parents=True, exist_ok=True)

parents=True creates parent directories as needed

exist_ok=True tells mkdir() to not error if the directory already exists

See the pathlib.Path.mkdir() docs.




回答5:


how about this os.system('mkdir -p %s' % directory_name )



来源:https://stackoverflow.com/questions/16029871/how-to-run-os-mkdir-with-p-option-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!