我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
在 Python 3.4 中,您还可以使用全新 pathlib 模块:
from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
if not path.parent.exists():
path.parent.mkdir(parents=True)
except OSError:
# handle error; you can also catch specific errors like
# FileExistsError and so on.
其他回答
在Python中做到这一点的最佳方法
#Devil
import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
os.makedirs(directory)
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
您可以使用 os.listdir 为此:
import os
if 'dirName' in os.listdir('parentFolderPath')
print('Directory Exists')
从 Python 3.5 开始, pathlib.Path.mkdir 有一个 exist_ok 旗帜:
from pathlib import Path
path = Path('/my/directory/filename.txt')
path.parent.mkdir(parents=True, exist_ok=True)
# path.parent ~ os.path.dirname(path)
此可重复创建目录,如果目录已经存在,则不会产生例外。
(就像 os.makedirs 得到 exist_ok 旗帜从 python 3.2 e.g os.makedirs(路径, exist_ok=True))
注意:当我发表这个答案时,没有其他提到的答案存在_OK...
在 Python3 中,OS.makedirs 支持设置 exist_ok. 默认设置是 False,这意味着如果目标目录已经存在,则将升级到 OSError. 通过设置 exist_ok 到 True,则将被忽略到 OSError(目录存在)并不会创建目录。
os.makedirs(path,exist_ok=True)
在 Python2 中, os.makedirs 不支持 exist_ok 设置. 在 heikki-toivonen 的答案中,您可以使用方法:
import os
import errno
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise