Skip to content
>GLB_
Go back

Creating Directories in Python

The os Module

Python’s os module provides a way to interact with the operating system. It includes functions for creating, removing, and checking the existence of directories and files. In this tutorial, we’ll use the os.path.exists and os.makedirs functions. This module contains the necessary functions to check for the existence of a directory and create it if it doesn’t exist.

import os

def create_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"Directory '{path}' created successfully.")
    else:
        print(f"Directory '{path}' already exists.")

# Example usage
directory_path = 'my_new_directory'
create_directory(directory_path)

Key points

Conclusion

Using the os module in Python, you can easily check for the existence of a directory and create it if necessary. This ensures that your scripts and applications can handle file operations without running into errors due to missing directories. With this approach, you can make your code more robust and error-resistant.


Share this post:

Previous Post
Understanding MAC Addresses: Hexadecimal, Binary, and Decimal Representations
Next Post
Route Summarization and Subnetting