Handle File Errors using Try-Except in Python
In Python, the try-except block allows handling file errors gracefully instead of causing the program to crash. When attempting file operations like reading or writing, unexpected issues (e.g., file not found, permission errors) can occur. The try block contains the file operation, while the except block catches and handles errors accordingly.
Examples
1. Handling File Not Found Error
If a file does not exist, trying to open it in read mode causes a FileNotFoundError. We can handle this using try-except.
main.py
try:
# Attempt to open a non-existent file
file = open("non_existent_file.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("Error: The file does not exist.")
Explanation:
- The
tryblock attempts to opennon_existent_file.txtin read mode. - Since the file does not exist, a
FileNotFoundErroris raised. - The
exceptblock catches this error and prints a user-friendly message.
Output:

2. Handling Permission Error for File
Trying to open a file without the necessary permissions raises a PermissionError.
Consider the following protected file.

We can handle it as shown below.
main.py
try:
# Attempt to open a restricted file
file = open("/root/protected_file.txt", "r")
content = file.read()
file.close()
except PermissionError:
print("Error: You do not have permission to access this file.")
Explanation:
- The
tryblock attempts to open/root/protected_file.txt, which may require administrator privileges. - If the script lacks the necessary permissions, a
PermissionErroris raised. - The
exceptblock catches the error and informs the user.
Output:

3. Handling File Read Errors
Errors may occur while reading a file (e.g., trying to read a binary file as text). We can catch such errors using try-except.
main.py
try:
# Attempt to read a file incorrectly
file = open("binary_file.bin", "r")
content = file.read()
file.close()
except UnicodeDecodeError:
print("Error: Unable to read the file as text.")
Explanation:
- The
tryblock attempts to open a binary filebinary_file.binin text mode. - Since binary files contain non-text data, reading as text may raise a
UnicodeDecodeError. - The
exceptblock handles this and provides a message.
Output:
Error: Unable to read the file as text.
4. Handling File Write Errors
Attempting to write to a read-only file may raise an IOError or PermissionError.
Consider the following read only file.

We can handle this as follows.
main.py
try:
# Attempt to write to a read-only file
file = open("readonly.txt", "w")
file.write("Trying to write to a read-only file.")
file.close()
except IOError:
print("Error: Cannot write to this file.")
Explanation:
- The
tryblock attempts to write toreadonly.txt, which may be set as read-only. - If writing fails, an
IOErroris raised. - The
exceptblock catches the error and provides a message.
Output:

Conclusion
In this tutorial, we covered scenarios using try-except to handle file errors effectively:
- File Not Found (
FileNotFoundError): Occurs when attempting to read a non-existent file. - Permission Denied (
PermissionError): Happens when accessing a file without necessary permissions. - Read Errors (
UnicodeDecodeError): Raised when a file is read incorrectly. - Write Errors (
IOError): Occurs when writing to a restricted file.
