gpt4 book ai didi

python - 在打开文件进行写入之前递归创建目录

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:54 26 4
gpt4 key购买 nike

我需要写入一个文件(截断),它所在的路径可能不存在)。例如,我想写入 /tmp/a/b/c/config,但 /tmp/a 本身可能不存在。然后,open('/tmp/a/b/c/config', 'w') 显然不起作用,因为它没有创建必要的目录。但是,我可以使用以下代码:

import os

config_value = 'Foo=Bar' # Temporary placeholder

config_dir = '/tmp/a/b/c' # Temporary placeholder
config_file_path = os.path.join(config_dir, 'config')

if not os.path.exists(config_dir):
os.makedirs(config_dir)

with open(config_file_path, 'w') as f:
f.write(config_value)

是否有更 Pythonic 的方法来做到这一点?知道 Python 2.x 和 Python 3.x 会很高兴(尽管由于依赖性原因,我在代码中使用 2.x)。

最佳答案

如果您在多个地方重复此模式,您可以创建自己的上下文管理器来扩展 open() 并重载 __enter__():

import os

class OpenCreateDirs(open):
def __enter__(self, filename, *args, **kwargs):
file_dir = os.path.dirname(filename)
if not os.path.exists(file_dir):
os.makedirs(file_dir)

super(OpenCreateDirs, self).__enter__(filename, *args, **kwargs)

然后你的代码变成:

import os

config_value = 'Foo=Bar' # Temporary placeholder
config_file_path = os.path.join('/tmp/a/b/c', 'config')

with OpenCreateDirs(config_file_path, 'w') as f:
f.write(config_value)

运行 with open(...) as f: 时调用的第一个方法是 open.__enter__()。因此,通过在调用 super(...).__enter__() 之前创建目录,您可以在尝试打开文件之前创建目录。

关于python - 在打开文件进行写入之前递归创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37711216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com