Error Handling in Files

When working with files, errors can occur for many reasons:

• File does not exist
• No permission to access file
• Disk full
• Wrong file mode

To prevent your program from crashing, Python provides exception handling using try and except.

BASIC TRY-EXCEPT EXAMPLE

try:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
except:
print("An error occurred while opening the file.")

If an error happens, the program will not stop — it will show the error message instead.

HANDLING SPECIFIC FILE ERRORS

1. FileNotFoundError

Occurs when the file does not exist.

try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the file name.")

2. PermissionError

Occurs when you don’t have permission to access the file.

try:
with open("data.txt", "w") as file:
file.write("Hello")
except PermissionError:
print("You do not have permission to access this file.")

3. Handling Multiple Exceptions

try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print("Some other error occurred:", e)

USING ELSE AND FINALLY

Else Block

Runs if no error occurs.

Finally Block

Runs no matter what (used for cleanup).

try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found.")
else:
print(file.read())
file.close()
finally:
print("File operation completed.")

BEST PRACTICE: WITH + TRY

try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)

Using with automatically closes the file even if an error occurs.

WHY ERROR HANDLING IS IMPORTANT

• Prevents program crashes
• Makes your program professional
• Helps debug problems easily
• Improves user experience

KEY TAKEAWAYS

• Use try and except to handle file errors
• Handle specific exceptions when possible
• Use with statement for safe file handling
• Use finally for cleanup tasks

Error handling is an essential skill for building reliable and professional Python applications.

Home » PYTHON INTERMEDIATE (PYI) > File Handling > Error Handling in Files