Python Context Manager for File Handling

By: fyvo July 24, 2025 Algorithms

Description

This Python snippet demonstrates how to create a custom context manager for robust file handling. It uses the `__enter__` and `__exit__` methods to automatically manage resource allocation and deallocation, ensuring files are always closed even if exceptions occur during operations. This pattern promotes cleaner and safer code by centralizing setup and teardown logic.

Code Snippet

import os

class FileHandler:
    """
    A simple context manager for handling file operations,
    ensuring files are properly closed even if errors occur.
    """
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        print(f"Opening file: {self.filename} in '{self.mode}' mode...")
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
            print(f"File: {self.filename} closed.")
        if exc_type:
            print(f"An exception occurred: {exc_type.__name__}: {exc_val}")
        return False # Propagate exception if any

# --- Example Usage ---
# Create a dummy file for writing
with open("my_test_file.txt", "w") as f:
    f.write("This is a test line.\n")

# Use the custom context manager
with FileHandler("my_test_file.txt", "r") as f:
    content = f.read()
    print(f"Content read: \n{content}")

# Example with an error to show __exit__ handling
try:
    with FileHandler("non_existent_file.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("Caught FileNotFoundError as expected.")

# Clean up
if os.path.exists("my_test_file.txt"):
    os.remove("my_test_file.txt")

Discussion (0)