Create a nested directory in Python

0 votes
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? I checked using the following code:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

f = file(filename)
 

I think I missed os.path.exists . This is what I have now:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
 

Is there a flag for "open", that makes this happen automatically?
Oct 16, 2018 in Python by ana1504.k
• 7,870 points
113 views

1 answer to this question.

0 votes
Try os.path.exists, and consider os.makedirs for the creation.

import os
if not os.path.exists(directory):
    os.makedirs(directory)
 

There's also race condition - if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

Try the following:

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
answered Oct 16, 2018 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

is it possible to create zip of a directory in Python?

Please go through this code. This should ...READ MORE

answered Jul 10 in Python by Arvind
• 2,520 points
18 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
79 views
0 votes
1 answer

Create and open a file in Python

file = open('text.txt', 'w+) READ MORE

answered May 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
47 views
0 votes
1 answer

How do you create nested dict in Python?

It is important to remember when using ...READ MORE

answered Aug 16, 2018 in Python by Priyaj
• 56,200 points
1,075 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 views
0 votes
1 answer

Create a GUID/UUID in Python

The uuid module, in Python 2.5 and ...READ MORE

answered Nov 22, 2018 in Python by SDeb
• 13,160 points
55 views
0 votes
1 answer

How to create a GUID/UUID in Python

The uuid module, in Python 2.5 and ...READ MORE

answered Jan 29 in Python by SDeb
• 13,160 points
90 views