Recursively Create Directories Prior To Opening File For Writing
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, op
Solution 1:
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)
ifnotos.path.exists(file_dir):
os.makedirs(file_dir)
super(OpenCreateDirs, self).__enter__(filename, *args, **kwargs)
Then your code becomes:
import os
config_value = 'Foo=Bar'# Temporary placeholder
config_file_path = os.path.join('/tmp/a/b/c', 'config')
withOpenCreateDirs(config_file_path, 'w') as f:
f.write(config_value)
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.
Post a Comment for "Recursively Create Directories Prior To Opening File For Writing"