Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically creating directories with file output [duplicate]

Tags:

python

file-io

Possible Duplicate:
mkdir -p functionality in python

Say I want to make a file:

filename = "/foo/bar/baz.txt"  with open(filename, "w") as f:     f.write("FOOBAR") 

This gives an IOError, since /foo/bar does not exist.

What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call os.path.exists and os.mkdir on every single one (i.e., /foo, then /foo/bar)?

like image 709
Phil Avatar asked Sep 20 '12 17:09

Phil


People also ask

How do I automatically create a directory in Python?

Using os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os. makedirs() method will create them all.

Does Python open create folders?

Python's OS module provides an another function to create a directories i.e. os. makedirs(name) will create the directory on given path, also if any intermediate-level directory don't exists then it will create that too. Its just like mkdir -p command in linux.

How do you create a directory if it doesn't exist in Python?

To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.

How do I get the current working directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .


1 Answers

In Python 3.2+, you can elegantly do the following:

 import os  filename = "/foo/bar/baz.txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f:     f.write("FOOBAR")  

In older python, there is a less elegant way:

The os.makedirs function does this. Try the following:

import os import errno  filename = "/foo/bar/baz.txt" if not os.path.exists(os.path.dirname(filename)):     try:         os.makedirs(os.path.dirname(filename))     except OSError as exc: # Guard against race condition         if exc.errno != errno.EEXIST:             raise  with open(filename, "w") as f:     f.write("FOOBAR")  

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


like image 80
Krumelur Avatar answered Oct 29 '22 11:10

Krumelur