我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
检查是否有一个目录,并在需要时创建它。
if not os.path.exists(d):
os.makedirs(d)
import errno
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
import tempfile
d = tempfile.mkdtemp()
有一个新的路径对象(如3.4)与许多方法,你会想使用路径 - 其中一个是 mkdir。
首先,相关进口:
from pathlib import Path
import tempfile
我们不需要处理 os.path.join 现在 - 只是加入路径部分与一个 /:
directory = Path(tempfile.gettempdir()) / 'sodata'
然后我无力地确保目录存在 - 存在_ok 论点在 Python 3.5 中出现:
directory.mkdir(exist_ok=True)
下面是文档的相关部分:
如果 exist_ok 是真实的,FileExistsError 例外将被忽略(与 POSIX mkdir -p 命令相同的行为),但只有如果最后的路径组件不是现有的非指南文件。
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
logger.info("todays_file exists: " + str(todays_file))
df = pd.read_json(str(todays_file))
路径对象必须在等待路径可以使用的其他API之前被强迫到Str。
也许Pandas应该更新以接受抽象基础类,os.PathLike的例子。
其他回答
检查是否有一个目录,并在需要时创建它。
if not os.path.exists(d):
os.makedirs(d)
import errno
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
import tempfile
d = tempfile.mkdtemp()
有一个新的路径对象(如3.4)与许多方法,你会想使用路径 - 其中一个是 mkdir。
首先,相关进口:
from pathlib import Path
import tempfile
我们不需要处理 os.path.join 现在 - 只是加入路径部分与一个 /:
directory = Path(tempfile.gettempdir()) / 'sodata'
然后我无力地确保目录存在 - 存在_ok 论点在 Python 3.5 中出现:
directory.mkdir(exist_ok=True)
下面是文档的相关部分:
如果 exist_ok 是真实的,FileExistsError 例外将被忽略(与 POSIX mkdir -p 命令相同的行为),但只有如果最后的路径组件不是现有的非指南文件。
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
logger.info("todays_file exists: " + str(todays_file))
df = pd.read_json(str(todays_file))
路径对象必须在等待路径可以使用的其他API之前被强迫到Str。
也许Pandas应该更新以接受抽象基础类,os.PathLike的例子。
在 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
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
在 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.
我找到了这个Q/A之后我被一些失败和错误我得到,当我在Python的目录工作,我在Python 3工作(在一个Anaconda虚拟环境中的3.5在一个Arch Linux x86_64系统)。
考虑此目录结构:
└── output/ ## dir
├── corpus ## file
├── corpus2/ ## dir
└── subdir/ ## dir
下面是我的实验 / 笔记,提供澄清:
# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist
import pathlib
""" Notes:
1. Include a trailing slash at the end of the directory path
("Method 1," below).
2. If a subdirectory in your intended path matches an existing file
with same name, you will get the following error:
"NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:
# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.
# out_dir = 'output/corpus3' ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/' ## works
# out_dir = 'output/corpus3/doc1' ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/' ## works
# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but no file created (os.makedirs creates dir, not files! ;-)
# out_dir = 'output/corpus2/tfidf/' ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/' ## works
# out_dir = 'output/corpus3/a/b/c/d/' ## works
# [2] https://docs.python.org/3/library/os.html#os.makedirs
# Uncomment these to run "Method 1":
#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)
# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.
# out_dir = 'output/corpus3' ## works
# out_dir = 'output/corpus3/' ## works
# out_dir = 'output/corpus3/doc1' ## works
# out_dir = 'output/corpus3/doc1/' ## works
# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/' ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/' ## works
# out_dir = 'output/corpus3/a/b/c/d/' ## works
# Uncomment these to run "Method 2":
#import os, errno
#try:
# os.makedirs(out_dir)
#except OSError as e:
# if e.errno != errno.EEXIST:
# raise
# ----------------------------------------------------------------------------
结论:我认为“方法2”更强大。
[1] 我如何安全地创建一张被锁定的目录?
[2] https://docs.python.org/3/图书馆/os.html#os.makedirs