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, 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