Gestión de Excepciones con Archivos

Cuando trabajamos con archivos, es muy común que ocurran errores. Por ejemplo, intentar abrir un archivo que no existe, o intentar escribir en un archivo sin los permisos adecuados. Es crucial manejar estas excepciones para que nuestro programa no se detenga inesperadamente.

Usamos los bloques try, except y finally para esto.

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}")