How to create a directory in Python

Published on Aug. 22, 2023, 12:15 p.m.

To create a directory in Python, you can use the os.makedirs() method. This function creates all the intermediate-level directories in the specified path if they do not already exist. Here is an example:

import os

directory = 'my_folder'
if not os.path.exists(directory):
    os.makedirs(directory)

In this example, we first define the name of the folder we want to create. We then check if the folder already exists using the os.path.exists() method. If the folder doesn’t exist, we create it using os.makedirs().

Alternatively, you can use the os.mkdir() method to create a single-level directory. Here is an example:

import os

directory = 'my_folder'
if not os.path.exists(directory):
    os.mkdir(directory)

In this example, we create a single-level directory instead of creating all intermediate-level directories.

Tags:

related content