我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
如果你考虑下列事项:
os.path.isdir('/tmp/dirname')
这意味着一个目录(路径)存在,而且是一个目录,所以对我来说,这就是我所需要的,所以我可以确保它是文件夹(不是文件)并且存在。
其他回答
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
对于单线解决方案,您可以使用 IPython.utils.path.ensure_dir_exists():
from IPython.utils.path import ensure_dir_exists
ensure_dir_exists(dir)
从文档:确保一个目录存在,如果它不存在,试着创建它,并保护它免受一个赛车状态,如果另一个过程正在做同样的事情。
IPython 是一个扩展包,而不是标准图书馆的一部分。
我看到了Heikki Toivonen和A-B-B的答案,并思考了这种变异。
import os
import errno
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST or not os.path.isdir(path):
raise
最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:
from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)
使用此命令检查并创建 dir
if not os.path.isdir(test_img_dir):
os.mkdir(test_img_dir)