Python Guide Sidebar

Creating Directories in Python: A Complete Guide

In Python, directories (also known as folders) are an essential part of file management. You can perform various operations on directories such as creating ,renaming, deleting, and listing the contents of the directories. Python provides a built-in module called os to work with directories, which includes functions for all these operations.

Directories in Python are managed using the os and shutil modules. You can create, delete, and list directories easily. Functions like os.makedirs() and shutil.rmtree() make directory handling efficient and flexible.

Creating Directories

Creating directories in Python is straightforward with the os.mkdir() function. It allows you to create a single directory.

Syntax:

import os
os.mkdir("new_directory")



This will create a directory named new_directory in the current working directory.

Example 1: Creating a Directory

import os

# Create a new directory
directory_name = "example_directory"
os.mkdir(directory_name)

print(f"Directory '{directory_name}' created successfully.")

Explanation:

  • os.mkdir() creates a single directory. If the directory already exists, it raises a FileExistsError.
  • The directory is created in the current working directory unless a full path is provided.

Creating Parent Directories

Sometimes, you might need to create a directory along with its parent directories (if they don’t exist). For this purpose, use os.makedirs().

import os

# Create a parent directory along with subdirectories
os.makedirs("parent_folder/sub_folder", exist_ok=True)

print("Parent directory and subdirectory created successfully.")

Explanation:

  • os.makedirs() creates intermediate directories if they don’t already exist.
  • The exist_ok=True argument prevents the function from raising an error if the directory already exists.

Renaming Directories

Renaming a directory is similar to renaming files. Python provides the os.rename() function to rename directories.

Syntax:

import os
os.rename("old_directory", "new_directory")


Example 2: Renaming a Directory

import os

# Renaming a directory
old_name = "old_directory"
new_name = "new_directory"

os.rename(old_name, new_name)

print(f"Directory renamed from {old_name} to {new_name}")

Explanation:

  • os.rename() renames the directory.
  • If the new directory name already exists, the operation will overwrite it, which could result in loss of data in the existing directory.

Deleting Directories

To delete a directory, Python provides the os.rmdir() and os.remove() methods. However, they only work if the directory is empty. If the directory contains files , you need to use shutil.rmtree().

Syntax:

import os
os.rmdir("empty_directory")

This will delete the directory empty_directory, but only if it is empty.

Example 3: Deleting an Empty Directory

import os

# Deleting an empty directory
directory_name = "empty_directory"

# Check if directory exists
if os.path.exists(directory_name):
    os.rmdir(directory_name)
    print(f"Directory '{directory_name}' deleted successfully.")
else:
    print(f"The directory '{directory_name}' does not exist.")

Explanation:

  • os.rmdir() will remove only empty directories.
  • If the directory is not empty, you need to use shutil.rmtree().

Deleting Non-Empty Directory

To delete a non-empty directory, use the shutil.rmtree() function, which recursively deletes all files and subdirectories inside the target directory.

import shutil

# Delete a non-empty directory
shutil.rmtree("non_empty_directory")

print("Non-empty directory deleted successfully.")

Explanation:

  • shutil.rmtree() deletes the entire directory tree, including all files and subdirectories.

Listing the Contents of a Directory

You can list all the files and subdirectories inside a directory using os.listdir().

Syntax:

import os
os.listdir("directory_name")

This returns a list of the names of the entries in the directory.

Example 4: Listing Directory Contents

import os

# List contents of a directory
directory_name = "example_directory"
contents = os.listdir(directory_name)

print(f"Contents of '{directory_name}':")
for item in contents:
    print(item)

Explanation:

  • os.listdir() returns a list of entries in the specified directory. These entries can be files or subdirectories.
  • You can iterate over the list to print each item.

Listing Only Files or Directories

If you want to list only the files or directories, you can use os.path functions like os.path.isdir() or os.path.isfile() in combination with os.listdir().

import os

# List only files in the directory
files = [f for f in os.listdir(directory_name) if os.path.isfile(os.path.join(directory_name, f))]
print(f"Files in '{directory_name}': {files}")

# List only subdirectories in the directory
directories = [d for d in os.listdir(directory_name) if os.path.isdir(os.path.join(directory_name, d))]
print(f"Subdirectories in '{directory_name}': {directories}")

Explanation:

  • This code lists only the files and directories separately by checking each item’s type.

Checking if a Directory Exists

Before performing any directory-related operation, it’s a good practice to check if the directory exists. You can use os.path.exists() or os.path.isdir() for this purpose.

Example 5: Checking If a Directory Exists

import os

# Check if a directory exists
directory_name = "example_directory"
if os.path.exists(directory_name):
    print(f"The directory '{directory_name}' exists.")
else:
    print(f"The directory '{directory_name}' does not exist.")

Explanation:

  • os.path.exists() checks if the specified directory exists.
  • os.path.isdir() is another option that checks if the path is a directory.

Mini Project: Directory Organizer

In this mini-project, we’ll write a Python script that organizes files in a directory into subdirectories based on file type (e.g., images, text files, PDFs).

NOTE: provide your own directiories in “example_directories”.

import os
import shutil

def organize_directory(directory):
    # Define subdirectories for file types
    file_types = {
        "Images": [".jpg", ".png", ".gif"],
        "Text Files": [".txt", ".docx"],
        "PDFs": [".pdf"]
    }

    # Loop through all files in the directory
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        
        # Skip directories
        if os.path.isdir(file_path):
            continue
        
        # Determine the file type and move it to the respective folder
        for folder, extensions in file_types.items():
            if filename.lower().endswith(tuple(extensions)):
                # Create subdirectory if it doesn't exist
                subdirectory = os.path.join(directory, folder)
                os.makedirs(subdirectory, exist_ok=True)
                
                # Move file to the respective subdirectory
                shutil.move(file_path, os.path.join(subdirectory, filename))
                print(f"Moved '{filename}' to '{folder}' folder.")
                break

# Run the directory organizer
organize_directory("example_directory")


Explanation:

  • This script organizes files in the example_directory into subdirectories based on their file extension (e.g., images, text files, PDFs).
  • It creates the subdirectories if they don’t exist, and moves the files accordingly.

Interview Questions and Answers on Directories


Amazon

Q1: How can you check if a directory exists before performing any operations on it?
A1: You can use os.path.exists() or os.path.isdir() to check if the directory exists before performing operations like renaming, deleting, or listing its contents.

Google

Q2: Can you delete a non-empty directory in Python?
A2: Yes, to delete a non-empty directory in Python, you can use the shutil.rmtree() function, which removes the entire directory tree, including files and subdirectories.

Zoho

Q3: How would you create a directory along with its parent directories if they don’t already exist?
A3: You can use os.makedirs() to create a directory along with any necessary parent directories. The exist_ok=True argument allows you to avoid errors if the directory already exists.

Infosys

Q4: How would you list only files (not directories) in a given directory?
A4: You can use os.listdir() in combination with os.path.isfile() to list only files in a directory, as shown in the example above.

TCS

Q5: What happens if you try to rename a directory to an existing directory?
A5: If you try to rename a directory to an existing directory, Python will raise a FileExistsError unless you overwrite the existing directory (which is generally not recommended).

Conclusion

Working with directories in Python is simple and efficient using the os and shutil modules. Whether you’re creating , renaming, deleting, or listing the contents of creating , Python provides powerful tools to handle these operations. It’s always important to check if directories exist before performing any operation and to handle potential errors to ensure smooth execution. With the techniques outlined in this guide, you can confidently manage directories in your Python programs