Create directories recursively before opening a file for writing

I need to write to a file (truncation), and the path that it itself may not exist). For example, I want to write /tmp/a/b/c/config, but it /tmp/amay not exist. Then open('/tmp/a/b/c/config', 'w')it will not work, obviously, since it does not create 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)

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

+4
source share
1 answer

, , 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__(), .

+2

All Articles