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:
import os, os.path
import errno
# Taken from https://stackoverflow.com/a/600612/119527
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
def safe_open_w(path):
''' Open "path" for writing, creating any parent directories as needed.
'''
mkdir_p(os.path.dirname(path))
return open(path, 'w')
with safe_open_w('/Users/bill/output/output-text.txt') as f:
f.write(...)
Updated for Python 3:
import os, os.path
def safe_open_w(path):
''' Open "path" for writing, creating any parent directories as needed.
'''
os.makedirs(os.path.dirname(path), exist_ok=True)
return open(path, 'w')
with safe_open_w('/Users/bill/output/output-text.txt') as f:
f.write(...)