How to Create a Folder in Current Directory in Python

Here are two ways to create a folder in the current working directory in Python:

  1. Using os.mkdir()
  2. Using os.makedirs()

Method 1: Using os.mkdir()

The os.mkdir() method is used to create a folder in the current working directory. It creates only the final target directory and will fail if the parent directory doesn’t exist.

Here is the current working directory before creating a new folder:

Screenshot of before creating a new folder in current working directory

import os

# Define the name of the directory to be created
folder_name = "new_dir"

path = os.path.join(".", folder_name) # Path relative to the current directory

try:
  os.mkdir(path)
  print(f"Directory '{folder_name}' created.")
except FileExistsError:
  print(f"Directory '{folder_name}' already exists.")

Output

Directory 'new_dir' created.

Output Screenshot of Creating a Folder in Current Directory in Python

Method 2: Using os.makedirs()

The os.makedirs() method is similar to os.mkdir(), but it can also create intermediate directories if they don’t exist. This is helpful if you need to create a nested directory structure in one go.

import os

# Define the name of the nested directory to be created
nested_folder = "./nested/sub_folder"

try:
  # 'exist_ok=True' prevents an error if the directory already exists
  os.makedirs(nested_folder, exist_ok=True)
  print(f"Nested directories '{nested_folder}' created.")
except FileExistsError:
  print(f"Directory '{nested_folder}' already exists.")

Output

Nested directories './nested/sub_folder' created.

Screenshot of os.makedirs() method to create nested directory

In this example, os.makedirs() function creates both new_folder and sub_folder if they don’t exist.

The exist_ok=True parameter allows the function to complete successfully even if the directories already exist, preventing a FileExistsError.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.