我需要写入一个文件(截断),并且它本身所在的路径可能不存在)。例如,我想写信给/tmp/a/b/c/config
, but /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:
is open.__enter__()
。因此,通过在调用之前创建目录super(...).__enter__()
,您在尝试打开文件之前创建目录。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)