我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
从 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...
其他回答
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
查看 os.makedirs: (它确保完整的路径存在) 要处理可能存在的目录的事实,查找 OSError. (如果存在_ok 是假的(默认情况下),如果目标目录已经存在,则会升起 OSError。
import os
try:
os.makedirs('./path/to/somewhere')
except OSError:
pass
你可以使用Megath。
# Create a directory and any missing ancestor directories.
# If the directory already exists, do nothing.
from distutils.dir_util import mkpath
mkpath("test")
请注意,它也将创建祖先目录。
它适用于Python 2和3。
如果您正在写一个文件到一个变量路径,您可以在文件路径上使用此文件,以确保母目录创建。
from pathlib import Path
path_to_file = Path("zero/or/more/directories/file.ext")
parent_directory_of_file = path_to_file.parent
parent_directory_of_file.mkdir(parents=True, exist_ok=True)
工作,即使 path_to_file 是 file.ext (零目录深)。
查看 pathlib.PurePath.parent 和 pathlib.Path.mkdir。
在 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.