31

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.

codeforester
  • 28,846
  • 11
  • 78
  • 104
Billz
  • 7,099
  • 6
  • 30
  • 33
  • I've been using [this snippet](http://code.activestate.com/recipes/82465-a-friendly-mkdir/) for years and years. – dabhaid May 21 '14 at 21:37

5 Answers5

47

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(...)
Jonathon Reinhart
  • 116,671
  • 27
  • 221
  • 298
18

For Python 3 can use with pathlib.Path:

from pathlib import Path

p = Path('Users'/'bill'/'output')
p.mkdir(exist_ok=True)
(p / 'output-text.txt').open('w').write(...)
BLimitless
  • 627
  • 2
  • 13
Yakir Tsuberi
  • 793
  • 1
  • 6
  • 12
  • 4
    This should be the accepted answer in 2020. There is no need to mess with custom functions and the os module anymore. – Jeff Wright Aug 09 '20 at 15:46
  • 1
    Couldn't get this working at all in W10 (using `WindowsPath`)... – mike rodent Oct 24 '20 at 13:49
  • 2
    there's a syntax error here. it should be `Path('Users/bill/output')` or `Path('Users') / 'bill' / 'output'` – ZeitPolizei Jan 26 '21 at 13:04
  • [You still need to close the file, even with `pathlib`.](https://stackoverflow.com/questions/61405654/recommended-way-of-closing-files-using-pathlib-module) – Leponzo Feb 01 '21 at 20:40
15

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))
huu
  • 5,894
  • 1
  • 31
  • 46
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

Community
  • 1
  • 1
Alex Gidan
  • 2,332
  • 14
  • 26
0

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)
(p / 'output-text.txt').open('w').write(...)
Hagbard
  • 2,139
  • 2
  • 16
  • 42