在打开文件进行写入之前以递归方式创建目录 [英] Recursively create directories prior to opening file for writing

查看:48
本文介绍了在打开文件进行写入之前以递归方式创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write to a file (truncating) and the path it is on itself might not exist). For example, I want to write to /tmp/a/b/c/config, but /tmp/a itself might not exist. Then, open('/tmp/a/b/c/config', 'w') would not work, obviously, since it doesn't make the necessary directories. However, I can work with the following code:

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)

还有更多的Python方式可以做到这一点吗?知道Python 2.x和Python 3.x都很好(尽管由于依赖性,我在代码中使用了2.x).

Is there a more Pythonic way to do this? Both Python 2.x and Python 3.x would be nice to know (even though I use 2.x in my code, due to dependency reasons).

推荐答案

如果要在多个位置重复此模式,则可以创建自己的上下文管理器,以扩展 open()并重载<代码> __ enter __():

If you're repeating this pattern in multiple places, you could create your own Context Manager that extends open() and overloads __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)

使用open(...)作为f:运行时,要调用的第一个方法是 open .__ enter __().因此,通过在调用 super(...).__ enter __()之前创建目录,可以在尝试打开文件之前创建目录.

The first method to be called when you run with open(...) as f: is open.__enter__(). So by creating directories before calling super(...).__enter__(), you create the directories before attempting to open the file.

这篇关于在打开文件进行写入之前以递归方式创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆