Error handling is an essential aspect of file operations in Python, as it ensures your program can handle unexpected situations gracefully, such as trying to read a non-existent file or not having the proper permissions to write to a file. Here are some key points and examples related to error handling with file operations:
FileNotFoundError
Raised when trying to open a file that does not exist.
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
PermissionError
Raised when trying to access a file without the required permissions.
try:
with open('/root/secret_file.txt', 'r') as file:
content = file.read()
except PermissionError:
print("You do not have the permission to access this file.")
IOError
A more general error related to I/O operations (reading/writing).
try:
with open('example.txt', 'r') as file:
content = file.read()
except IOError:
print("An I/O error occurred.")
try
and except
BlocksTo handle exceptions, use try
and except
blocks. This allows your program to catch and respond to exceptions without crashing.
Example:
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the file name and try again.")
except PermissionError:
print("Permission denied. Please check your permissions.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
You can handle multiple exceptions in a single block if the handling logic is the same.
Example:
try:
with open('example.txt', 'r') as file:
content = file.read()
except (FileNotFoundError, PermissionError) as e:
print(f"An error occurred: {e}")
The finally
block is used to execute code regardless of whether an exception was raised or not. This is useful for cleanup actions, like closing a file.
Example:
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # Ensure the file is closed
else
with try
The else
block executes if the try
block did not raise an exception. This is useful for code that should run only if no error occurred.
Example:
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully!")
Combining all these aspects into a comprehensive example:
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the file name and try again.")
except PermissionError:
print("Permission denied. Please check your permissions.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("File read successfully!")
print(content)
finally:
if 'file' in locals() and not file.closed:
file.close()
print("File closed.")
You can also define custom exceptions to handle specific cases in your file operations:
class CustomFileError(Exception):
pass
try:
with open('example.txt', 'r') as file:
if not file.readable():
raise CustomFileError("File is not readable.")
content = file.read()
except CustomFileError as e:
print(e)
except Exception as e:
print(f"An error occurred: {e}")