How can I safely create a nested directory in Python?

| | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

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? Here is what I tried:

import os

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


f = file(filename)

Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now:

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

Is there a flag for "open", that makes this happen automatically?

👻 Read also: what is the best laptop for engineering students?

How can I safely create a nested directory in Python? dirname: Questions

os.path.dirname(__file__) returns empty

2 answers

I want to get the path of the current directory under which a .py file is executed.

For example a simple file D: with code:

import os

print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)

It is weird that the output is:


I am expecting the same results from the getcwd() and path.dirname().

Given os.path.abspath = os.path.dirname + os.path.basename, why


returns empty?


Answer #1

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use


How can I safely create a nested directory in Python? dirname: Questions

What is the difference between os.path.basename() and os.path.dirname()?

2 answers

What is the difference between os.path.basename() and os.path.dirname()?

I already searched for answers and read some links, but didn"t understand. Can anyone give a simple explanation?


Answer #1

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of "/foo/bar/item" is "/foo/bar".

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of "/foo/bar/item" returns "item"


Python"s os.makedirs doesn"t understand "~" in my path

1 answers

I have a little problem with ~ in my paths.

This code example creates some directories called "~/some_dir" and do not understand that I wanted to create some_dir in my home directory.

my_dir = "~/some_dir"
if not os.path.exists(my_dir):

Note this is on a Linux-based system.


Answer #1

You need to expand the tilde manually:

my_dir = os.path.expanduser("~/some_dir")


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method