Course contentsShow
← Python
Lesson 712 of 1,06011. Standard Library EssentialsFree lesson

Performing Common Filesystem Operations

Gain the skills to create, rename, move, and delete files or directories programmatically while ensuring robust error handling for common filesystem exceptions.

In this lesson, you will learn how to programmatically manipulate files and directories while using robust error handling to manage filesystem volatility.

When working with the filesystem, you aren’t just writing code; you are interacting with a shared resource that can change unexpectedly. A file you intend to move might have been deleted by another process, or a directory you want to create might already exist. Python’s os and shutil modules provide the tools to perform these tasks, but safety requires catching exceptions like OSError, FileNotFoundError, and FileExistsError.

Core Operations with os and shutil

For basic operations, we use the os module for tasks like renaming and removing, while shutil is the go-to for high-level operations like moving or copying entire directory trees.

import os
import shutil

# Creating a directory safely
try:
    os.makedirs('data/logs', exist_ok=True)
except OSError as e:
    print(f"Error creating directory: {e}")

# Renaming a file
try:
    os.rename('old_name.txt', 'new_name.txt')
except FileNotFoundError:
    print("Source file does not exist.")

# Moving a file (shutil handles cross-filesystem moves)
try:
    shutil.move('new_name.txt', 'data/logs/')
except Exception as e:
    print(f"Failed to move file: {e}")

The Importance of Robust Error Handling

Because the filesystem is an external system, you should always wrap your operations in try-except blocks. If you attempt to delete a file that is currently locked by the operating system, or if you lack the necessary permissions to write to a folder, your script will crash unless you anticipate these OSError variations.

By checking if a directory exists (using os.path.exists) or using exist_ok=True in os.makedirs, you prevent "race conditions" where your script tries to create something that a previous run already established. Treating the filesystem as inherently unpredictable makes your code resilient and professional.

Key Takeaway: Always wrap filesystem operations in exception handlers and use specific flags like exist_ok to manage the inherent volatility of the operating system.