我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
在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)
在 Python ≥ 3.5 上使用 pathlib.Path.mkdir:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
对于旧版本的Python,我看到两个答案有良好的品质,每一个有一个小错误,所以我会给我的答案:
import os
if not os.path.exists(directory):
os.makedirs(directory)
正如评论和其他地方所指出的那样,有一个赛事状态 - 如果目录在 os.path.exists 和 os.makedirs 呼叫之间创建, os.makedirs 会失败 OSError. 不幸的是,包装捕捉 OSError 和继续不是虚假的,因为它会忽略由于其他因素创建目录的失败,如不够的许可,完整的磁盘等。
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
否则,可能有第二个 os.path.exists,但假设另一个创建了目录后第一次检查,然后删除它之前的第二个 - 我们仍然可以被误导。
现代版本的Python改进这个代码相当一点,两者都通过曝光FileExistsError(在3.3+)。
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...和允许一个关键词论点给os.makedirs称为 exist_ok(在3.2+)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
关于这种情况的具体性
您在某个路径上提供一个特定的文件,然后从文件路径中提取目录,然后确保您有目录后,您试图打开阅读的文件。
import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
你的最终目标是打开这个文件,你最初表示,写作,但你基本上接近这个目标(基于你的代码),如此,打开文件阅读:
如果不是 os.path.exists(地址): os.makedirs(地址) f = 文件(文件名)
為什麼你會為你期望在那裡並能夠閱讀的檔案製作一個目錄?
只是试着打开文件。
with open(filepath) as my_file:
do_stuff(my_file)
import errno
try:
with open(filepath) as my_file:
do_stuff(my_file)
except IOError as error:
if error.errno == errno.ENOENT:
print 'ignoring error because directory or file is not there'
else:
raise
假设我们对写作开放
在这种情况下,我们可能不会遇到任何竞赛条件,所以只是做你是,但请注意,写作,你需要打开W模式(或一个添加)。
import os
if not os.path.exists(directory):
os.makedirs(directory)
with open(filepath, 'w') as my_file:
do_stuff(my_file)
import os
import errno
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise
with open(filepath, 'w') as my_file:
do_stuff(my_file)
在创建目录之前,您必须设置完整的路径:
import os,sys,inspect
import pathlib
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"
if not os.path.exists(your_folder):
pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
这对我工作,我希望这对你也工作。
在 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