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.
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.withcloses 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.
elseruns only if no error happened.finallyalways runs — useful for clean-up.
Common exceptions to know
| Exception | Typical cause |
|---|---|
ValueError | Right type, wrong value — int("abc") |
TypeError | Wrong type — "5" + 5 |
KeyError | Missing dictionary key |
IndexError | List index out of range |
FileNotFoundError | File does not exist at that path |
ZeroDivisionError | Dividing 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.