LearnFrenzy
Sign in Take a free test

Working with Data · Lesson 6 of 6

Python Files and Error Handling: Read, Write and Never Crash

Read and write text and CSV files safely with "with", and handle bad input and missing files with try / except — the difference between a script and a real program.

11 min read Intermediate Updated Nov 5, 2026 Reviewed by Saurabh Samir

A program that crashes the moment a user types "abc" instead of a number, or when a file is missing, is not finished. This lesson covers two skills that make your code dependable: working with files and handling errors.

Writing and reading a text file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("DBMS: revise normalization\n")
    f.write("OS: revise deadlocks\n")

with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
  • "w" writes (and replaces any existing content), "a" appends, "r" reads.
  • with closes the file automatically, even if an error happens inside the block. Always use it.
  • encoding="utf-8" avoids problems with special characters like ₹ or Hindi text, especially on Windows.

Reading a CSV file

import csv

with open("marks.csv", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)          # first row = column names
    for row in reader:
        print(row["name"], row["marks"])

DictReader gives each row as a dictionary — exactly the list-of-dictionaries pattern from the previous lesson. (Later, in data analytics, you will use pandas for bigger files.)

Handling errors with try / except

while True:
    try:
        age = int(input("Enter your age: "))
        break
    except ValueError:
        print("Please enter a number, like 21.")

If int() fails, Python jumps to the except block instead of crashing, and the loop asks again.

Catch specific errors

try:
    with open("marks.csv", encoding="utf-8") as f:
        data = f.read()
except FileNotFoundError:
    print("marks.csv not found — check the file name and folder.")
except PermissionError:
    print("No permission to read marks.csv.")
else:
    print("Loaded", len(data), "characters")
finally:
    print("Done")

Avoid a bare except: that catches everything. It hides real bugs (even typos in variable names) and makes debugging painful. Catch the specific errors you expect.

  • else runs only if no error happened.
  • finally always runs — useful for clean-up.

Common exceptions to know

ExceptionTypical cause
ValueErrorRight type, wrong value — int("abc")
TypeErrorWrong type — "5" + 5
KeyErrorMissing dictionary key
IndexErrorList index out of range
FileNotFoundErrorFile does not exist at that path
ZeroDivisionErrorDividing by zero

Raising your own errors

def set_cgpa(value):
    if not 0 <= value <= 10:
        raise ValueError("CGPA must be between 0 and 10")
    return value

Raising a clear error early is far better than letting a wrong value travel through your program and cause a confusing problem later.

Try it yourself: Build an expense logger: ask for an item and amount in a loop, reject invalid amounts with try / except, append each entry to expenses.csv, and print the total when the user types "done". This is the start of the Expense Tracker project on this page.

Common interview questions

Try answering each one aloud before you open it.

1Why use the with statement for files?

It is a context manager that guarantees the file is closed when the block ends, even if an exception occurs, preventing resource leaks.

2What is the difference between else and finally in try/except?

else runs only when no exception was raised in the try block; finally always runs, whether or not an exception occurred.

3Why should you catch specific exceptions?

Catching everything hides unrelated bugs and makes failures silent. Specific exceptions let you handle expected problems and still see real errors.

Practise this

Build something with it

FAQs

Where does Python look for my file?

In the current working directory — usually the folder you ran the script from. Use a full path or the pathlib module if you are unsure.

Should I use the csv module or pandas?

csv is built in and perfect for small, simple files. pandas is better for analysis, large files and data cleaning.

References & further reading

Finished this lesson?

Mark it complete. Create a free account to save it on every device.

Take the Skill Check

Search LearnFrenzy

Esc

Quick links