Course contentsShow
← Python
Lesson 363 of 1,0606. Error Handling and File I/OFree lesson

Creating and Removing Directories Programmatically

Learners will safely construct complex directory trees and perform cleanups while handling potential errors like existing or missing target paths.

In this lesson, you will learn how to safely build and destroy directory structures while ensuring your program doesn't crash when it encounters an existing or missing folder.

Creating Directories

When working with the pathlib module, you create directories using the .mkdir() method. However, a common runtime error occurs if you try to create a folder that already exists. To handle this, you can set the exist_ok parameter to True. This effectively implements the "Easier to Ask for Forgiveness than Permission" (EAFP) principle, preventing an FileExistsError from stopping your script.

from pathlib import Path

data_dir = Path("data/logs")

# parents=True creates missing parent folders (like 'data')
# exist_ok=True prevents errors if 'logs' already exists
try:
    data_dir.mkdir(parents=True, exist_ok=True)
    print("Directory ready!")
except OSError as e:
    print(f"Failed to create directory: {e}")

Removing Directories

Removing directories is equally sensitive. You can use .rmdir() to remove an empty directory, but it will raise an OSError if the folder contains files. For cleaning up, it is often safer to verify the directory is empty or handle the exception explicitly.

target = Path("temp_folder")

try:
    target.rmdir()
    print("Directory removed successfully.")
except FileNotFoundError:
    print("Directory didn't exist, nothing to remove.")
except OSError:
    print("Directory is not empty; cannot remove safely.")

Best Practices for Cleanups

When building complex directory trees, treat these operations as part of your resource management workflow. If your script creates a temporary workspace, use a try...finally block to ensure that no matter what happens during your data processing, you attempt to clean up the workspace at the end. This prevents your drive from filling up with orphaned folders if an error occurs mid-process. Always use pathlib to ensure your code works across different operating systems, as it handles path separators (like / vs \) automatically.

Key Takeaway: Use exist_ok=True to prevent creation errors and always wrap directory removal in error handling to avoid crashes when targets are missing or not empty.