Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
7 views
in Python by (4k points)
edited by

How can I check the file going to be written exists in the directory, and if not , How can I create directory in Python. I already tried this:

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)

But I missed os.path.exists ,and now I have:

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

Can I make this happen automatically, is there an "open" flag for the same?

1 Answer

0 votes
by (46k points)
edited by

There are several methods to perform this task, I will discuss a few with you:

  1. You can try os.path.existsand for creation consider  os.makedirsfor creation.

 import os

if not os.path.exists(directory): 

    os.makedirs(directory) 

 If you face an error you can trap and examine it using embedded error code

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

    2. If you are using Python 3.5+ you can use pathlib, it creates directory without raising an exception if directory already exists. I you want to create the parents or don't need it, then skip the parents argument

 import pathlib

pathlib.Path('/my/directory').mkdir(parents=1, exist_ok=1)

To know more about this you can have a look at the following video tutorial:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

+1 vote
2 answers
0 votes
2 answers
+1 vote
1 answer
+3 votes
2 answers
0 votes
1 answer

Browse Categories

...