create nested directory in python

How to Create Nested Directory in Python

Python allows you to create, update and remove directories on your system. Sometimes you may need to create nested directory in Python, as a part of your application or website. There are several ways to do this. In this article, we will learn how to create nested directory in Python.


How to Create Nested Directory in Python

We will create /home/dir1/dir2 for our examples.


1. Using pathlib

Python 3.5 and above provide pathlib module to easily work with files & directories. You can use it as shown below to quickly create nested folders.

from pathlib import Path
Path("/home/dir1/dir2").mkdir(parents=True, exist_ok=True)

In the above code, we import Path() function from pathlib library. In that, we call mkdir() function to create directories. It takes two arguments, parents & exist_ok. parents is set to False by default so that it throws a FileNotFound Error exception if the parent folder (e.g. /home above) of nested folder does not exist. We will set it to True, to ignore this option. exist_ok is also set to False by default so that it throws a FileExistsError exception if the folder exists. We will set it to True, to avoid raising exceptions.

Please note, you need to provide the absolute path and not relative path in the above command.


2. Using os.makedirs

In python 3.2 and above, you can use os.makedirs to create nested directories. You just need to pass the path to nested directory.

import os
os.makedirs("/home/dir1/dir2")

It does not raise an exception even if the directory exists.

However, if you still want to raise an exception in case the folder exists, you can modify the above code as shown below, to add a try…catch block.

import os

try:
    os.makedirs("/dir1/dir2")
except FileExistsError:
    print("File already exists")


3. Using distutils.dir_util

Like os.makedirs, you can also use distutil.dir_util to create nested directories.

import distutils.dir_util

distutils.dir_util.mkpath("/home/dir1/dir2")

In this article, we have learnt several simple ways to create nested directories in Python.

Also read:

How to Find Package for File in Ubuntu
How to Prompt for User Input in Shell Script
How to Uninstall SQL Server in Ubuntu
How to Install or Upgrade Software from Unsupported Release
Shell Script to Check if Script is Already Running

Leave a Reply

Your email address will not be published. Required fields are marked *