How do I using with open() as f: ...
to write the file in a directory that doesn’t exist.
For example:
JavaScript
x
3
1
with open('/Users/bill/output/output-text.txt', 'w') as file_to_write:
2
file_to_write.write("{}n".format(result))
3
Let’s say the /Users/bill/output/
directory doesn’t exist. If the directory doesn’t exist just create the directory and write the file there.
Advertisement
Answer
You need to first create the directory.
The mkdir -p
implementation from this answer will do just what you want. mkdir -p
will create any parent directories as required, and silently do nothing if it already exists.
Here I’ve implemented a safe_open_w()
method which calls mkdir_p
on the directory part of the path, before opening the file for writing:
JavaScript
1
21
21
1
import os, os.path
2
import errno
3
4
# Taken from https://stackoverflow.com/a/600612/119527
5
def mkdir_p(path):
6
try:
7
os.makedirs(path)
8
except OSError as exc: # Python >2.5
9
if exc.errno == errno.EEXIST and os.path.isdir(path):
10
pass
11
else: raise
12
13
def safe_open_w(path):
14
''' Open "path" for writing, creating any parent directories as needed.
15
'''
16
mkdir_p(os.path.dirname(path))
17
return open(path, 'w')
18
19
with safe_open_w('/Users/bill/output/output-text.txt') as f:
20
f.write( )
21
Updated for Python 3:
JavaScript
1
11
11
1
import os, os.path
2
3
def safe_open_w(path):
4
''' Open "path" for writing, creating any parent directories as needed.
5
'''
6
os.makedirs(os.path.dirname(path), exist_ok=True)
7
return open(path, 'w')
8
9
with safe_open_w('/Users/bill/output/output-text.txt') as f:
10
f.write( )
11