我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
如果您正在写一个文件到一个变量路径,您可以在文件路径上使用此文件,以确保母目录创建。
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。
其他回答
检查是否有一个目录,并在需要时创建它。
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的例子。
但我猜你的真正意图是创建一个文件和其主目录,因为它的内容全部在1命令。
您可以使用 fastcore 扩展到 pathlib: path.mk_write(数据)
from fastcore.utils import Path
Path('/dir/to/file.txt').mk_write('Hello World')
在Fastcore文档中查看更多
我下载了下面的文章,但这不是完全愚蠢的。
import os
dirname = 'create/me'
try:
os.makedirs(dirname)
except OSError:
if os.path.exists(dirname):
# We are nearly safe
pass
else:
# There was an error on creation, so make sure we know about it
raise
如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。
查看 os.makedirs: (它确保完整的路径存在) 要处理可能存在的目录的事实,查找 OSError. (如果存在_ok 是假的(默认情况下),如果目标目录已经存在,则会升起 OSError。
import os
try:
os.makedirs('./path/to/somewhere')
except OSError:
pass
使用此命令检查并创建 dir
if not os.path.isdir(test_img_dir):
os.mkdir(test_img_dir)