Start Coding

Topics

Python Directory Handling

Directory handling is a crucial aspect of file system management in Python. It allows developers to create, navigate, and manipulate directories efficiently. The os module provides powerful tools for these operations.

Creating Directories

To create a new directory, use the os.mkdir() function. For nested directories, employ os.makedirs().


import os

# Create a single directory
os.mkdir("new_folder")

# Create nested directories
os.makedirs("parent/child/grandchild")
    

Listing Directory Contents

The os.listdir() function returns a list of entries in a specified directory. For more detailed information, use os.scandir().


# List directory contents
print(os.listdir("."))

# Detailed directory scan
with os.scandir(".") as entries:
    for entry in entries:
        print(entry.name, "- Directory" if entry.is_dir() else "- File")
    

Changing the Current Working Directory

Navigate between directories using os.chdir(). This function changes the current working directory.


# Change directory
os.chdir("/path/to/new/directory")

# Print current working directory
print(os.getcwd())
    

Removing Directories

To delete an empty directory, use os.rmdir(). For removing directories with contents, utilize shutil.rmtree() from the shutil module.


import shutil

# Remove empty directory
os.rmdir("empty_folder")

# Remove directory and its contents
shutil.rmtree("non_empty_folder")
    

Best Practices

  • Always check for directory existence before performing operations.
  • Use absolute paths when working with critical system directories.
  • Handle exceptions to manage errors gracefully.
  • Be cautious when deleting directories, especially with shutil.rmtree().

Related Concepts

To enhance your understanding of Python file system operations, explore these related topics:

Mastering directory handling in Python is essential for efficient file system management and automation tasks. Practice these techniques to improve your skills in manipulating directories and files programmatically.