Python Create Directory

Introduction

Creating directories in Python is a straightforward task that can be accomplished using the os module and the pathlib module. These modules provide functions to create single directories as well as nested directories.

Using the os Module

The os module provides functions to interact with the operating system. To create directories, you can use the os.mkdir() function for single directories and os.makedirs() for nested directories.

os.mkdir()

The os.mkdir() function creates a single directory.

Syntax

import os

os.mkdir('directory_name')

Example

import os

# Creating a single directory
try:
    os.mkdir('example_dir')
    print("Directory 'example_dir' created successfully.")
except FileExistsError:
    print("Directory 'example_dir' already exists.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Directory 'example_dir' created successfully.

os.makedirs()

The os.makedirs() function creates directories recursively, meaning it can create nested directories.

Syntax

import os

os.makedirs('parent_dir/child_dir')

Example

import os

# Creating nested directories
try:
    os.makedirs('parent_dir/child_dir')
    print("Nested directories 'parent_dir/child_dir' created successfully.")
except FileExistsError:
    print("Directory 'parent_dir/child_dir' already exists.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Nested directories 'parent_dir/child_dir' created successfully.

Using the pathlib Module

The pathlib module in Python 3.4+ provides an object-oriented approach to handling filesystem paths. It includes the Path.mkdir() method for creating directories.

Example

from pathlib import Path

# Creating a single directory
path = Path('example_dir')
try:
    path.mkdir()
    print("Directory 'example_dir' created successfully.")
except FileExistsError:
    print("Directory 'example_dir' already exists.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Directory 'example_dir' created successfully.

Creating Nested Directories

You can create nested directories by setting the parents parameter to True.

from pathlib import Path

# Creating nested directories
path = Path('parent_dir/child_dir')
try:
    path.mkdir(parents=True, exist_ok=True)
    print("Nested directories 'parent_dir/child_dir' created successfully.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Nested directories 'parent_dir/child_dir' created successfully.

Handling Exceptions

It’s a good practice to handle exceptions that may occur during the creation of directories, such as FileExistsError and PermissionError.

Example

import os

# Creating a directory with exception handling
try:
    os.mkdir('example_dir')
    print("Directory 'example_dir' created successfully.")
except FileExistsError:
    print("Directory 'example_dir' already exists.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Directory 'example_dir' created successfully.

Conclusion

Creating directories in Python is simple and efficient using the os module and the pathlib module. The os.mkdir() function is suitable for creating single directories, while os.makedirs() is used for creating nested directories. The pathlib module provides a modern, object-oriented approach to filesystem paths and directory creation. By handling exceptions, you can ensure that your program responds appropriately to errors during the directory creation process. Understanding these methods is essential for file and directory management tasks in Python applications.

Leave a Comment

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

Scroll to Top