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

</>
Copy
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:

  1. The try block attempts to open non_existent_file.txt in read mode.
  2. Since the file does not exist, a FileNotFoundError is raised.
  3. The except block 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

</>
Copy
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:

  1. The try block attempts to open /root/protected_file.txt, which may require administrator privileges.
  2. If the script lacks the necessary permissions, a PermissionError is raised.
  3. The except block 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

</>
Copy
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:

  1. The try block attempts to open a binary file binary_file.bin in text mode.
  2. Since binary files contain non-text data, reading as text may raise a UnicodeDecodeError.
  3. The except block 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

</>
Copy
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:

  1. The try block attempts to write to readonly.txt, which may be set as read-only.
  2. If writing fails, an IOError is raised.
  3. The except block catches the error and provides a message.

Output:

Conclusion

In this tutorial, we covered scenarios using try-except to handle file errors effectively:

  1. File Not Found (FileNotFoundError): Occurs when attempting to read a non-existent file.
  2. Permission Denied (PermissionError): Happens when accessing a file without necessary permissions.
  3. Read Errors (UnicodeDecodeError): Raised when a file is read incorrectly.
  4. Write Errors (IOError): Occurs when writing to a restricted file.