49

How do I using with open() as f: ... to write the file in a directory that doesn't exist.

For example:

with open('/Users/bill/output/output-text.txt', 'w') as file_to_write: file_to_write.write("{}\n".format(result)) 

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.

1
  • I've been using this snippet for years and years. Commented May 21, 2014 at 21:37

5 Answers 5

70

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(...) 
Sign up to request clarification or add additional context in comments.

6 Comments

This is a great answer. Just for clarification, the mkdir_p function used in your code has to be defined as well, using the link provided. It does not come with Python.
@HuuNguyen Added that clarification, thanks. Still not sure why someone downvoted this.
For exc.errno == errno.EEXIST I got the error: NameError: global name 'errno' is not defined. Changing it to exc.errno == 17 worked.
@Jacob You need to import errno.
Nowadays, you can avoid the error handling by passing exists_ok=True to os.makedirs
|
48

Using pathlib.Path (in Python 3.5 and up, to support the exist_ok parameter):

from pathlib import Path p = Path('Users') / 'bill' / 'output' p.mkdir(exist_ok=True) with (p / 'output-text.txt').open('w') as opened_file: opened_file.write(...) 

2 Comments

This should be the accepted answer in 2020. There is no need to mess with custom functions and the os module anymore.
Note you may want to specify parents=True to get the expected behavior of creating all directories that don't exist for the file.
17

Make liberal use of the os module:

import os if not os.path.isdir('/Users/bill/output'): os.mkdir('/Users/bill/output') with open('/Users/bill/output/output-text.txt', 'w') as file_to_write: file_to_write.write("{}\n".format(result)) 

2 Comments

This doesn't handle making the intermediate directories as well.
Of course not, and this is a complete assumption on my part. I think /Users/bill exists though.
14

The answer given by Yakir Tsuberi is great but I would like to add that you need the parameter parents=True for nested folders as explained here. Thus, the code would look as follows:

from pathlib import Path p = Path('Users/bill/output') p.mkdir(parents=True, exist_ok=True) with (p / 'output-text.txt').open('w') as opened_file: opened_file.write(...) 

Comments

2

You can just create the path you want to create the file using os.makedirs:

import os import errno def make_dir(path): try: os.makedirs(path, exist_ok=True) # Python>3.2 except TypeError: try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise 

Source: this SO solution

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.