Exception Handling in File Operations
Work with errors in file handling.
9
try:
with open("data.csv", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The specified file was not found.")
4
Handling FileNotFoundError
The FileNotFoundError occurs when you try to open a file that doesn't exist. You can handle this error using a try-except block.
Example:
try:
# Tries to open a non-existent file
with open("missing_file.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file does not exist.")
All lessons in this course
- Reading Files
- Writing to Files
- File Modes
- Exception Handling in File Operations