判断文件要写入的目录是否存在,如果不存在,使用Python创建目录,最优雅的方法是什么?以下是我try 过的:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)

f = file(filename)

不知怎的,我错过了os.path.exists分(感谢kanja、Blair和Douglas).这就是我现在拥有的:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

有没有一个open()的旗帜,让这件事自动发生?

推荐答案

关于Python≥ 3.5,使用pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

对于较旧版本的Python,我看到了两个很好的答案,每个答案都有一个小缺陷,因此我将给出我的看法:

try os.path.exists,并考虑os.makedirs的创作.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

一种 Select 是捕获OSError并判断嵌入的错误代码(请参见Is there a cross-platform way of getting information from Python’s OSError):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.

根据应用程序的不同,并发操作的危险可能或多或少比其他因素(如文件权限)带来的危险更大或更小.在 Select 实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境.

Python的现代版本大大改进了这段代码,它们都是通过公开FileExistsError(在3.3+中)和...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

.并允许a keyword argument to os.makedirs called exist_ok(3.2+).

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

Python相关问答推荐

即使在可见的情况下也不相互作用

可变参数数量的重载类型(args或kwargs)

为什么这个带有List输入的简单numba函数这么慢

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

使用groupby Pandas的一些操作

如何创建一个缓冲区周围的一行与manim?

基于索引值的Pandas DataFrame条件填充

当递归函数的返回值未绑定到变量时,非局部变量不更新:

Plotly Dash Creating Interactive Graph下拉列表

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

Python全局变量递归得到不同的结果

在Python中计算连续天数

使用Python TCP套接字发送整数并使用C#接收—接收正确数据时出错

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

合并相似列表

上传文件并使用Panda打开时的Flask 问题

随机森林n_估计器的计算

时长超过24小时如何从Excel导入时长数据

仅取消堆叠最后三列

某些值的数值幂和**之间的差异