0Pricing
Python For Kids · Lesson

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

  1. Reading Files
  2. Writing to Files
  3. File Modes
  4. Exception Handling in File Operations
← Back to Python For Kids