Exception Handling with Files

When working with files, it is very common for errors to occur. For example, trying to open a file that doesn't exist, or attempting to write to a file without the proper permissions. It is crucial to handle these exceptions so that our program does not stop unexpectedly.

We use try, except, and finally blocks for this.

try:
    with open('non_existent_file.txt', 'r') as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("Error: The file 'non_existent_file.txt' was not found.")
except IOError as e:  # General I/O error
    print(f"An I/O error occurred: {e}")
except Exception as e:  # Catch any other unexpected errors
    print(f"An unexpected error occurred: {e}")
finally:
    # This block always executes, whether an error occurred or not
    # Useful for cleanup, though 'with' statement handles file closing
    print("Attempted file operation.")

print("-" * 30)

# Example with write permissions error (might need to run as non-admin in a protected folder)
try:
    # Try to write to a protected system file (e.g., in root of C: or /)
    # This might require specific permissions or fail on purpose
    with open('/etc/some_protected_file.txt', 'w') as f:  # Example for Linux/macOS
    # with open('C:\\Windows\\System32\\some_protected_file.txt', 'w') as f:  # Example for Windows
        f.write("Trying to write to a protected file.")
except PermissionError:
    print("Error: You don't have permission to write to this file or directory.")
except Exception as e:
    print(f"An error occurred: {e}")