Learn / Beginner / Lesson 12

Files and errors

13 min Tested on Python 3.15Updated By
In short

Use with open("file.txt") as f: to read or write a file — with closes it for you, even if something goes wrong. Wrap code that can fail in try / except to handle the error instead of crashing, and use raise to report a problem yourself.

Writing and reading a text file

Python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")

with open("notes.txt", encoding="utf-8") as f:
    content = f.read()
print(content)
Output
first line
second line
ModeMeaning
"r"read (the default)
"w"write — creates the file or empties an existing one
"a"append to the end

Reading line by line

Python
with open("todo.txt", "w", encoding="utf-8") as f:
    f.write("buy milk\ncall Ana\nfix bug\n")

with open("todo.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())
Output
1 buy milk
2 call Ana
3 fix bug

pathlib: the modern way

Python
from pathlib import Path

path = Path("hello.txt")
path.write_text("Hi from pathlib\n", encoding="utf-8")
print(path.read_text(encoding="utf-8").strip())
print(path.exists(), path.suffix, path.stem)
Output
Hi from pathlib
True .txt hello

CSV files

Python
import csv

with open("sales.csv", "w", newline="", encoding="utf-8") as f:
    f.write("product,qty\nmug,3\ntea,5\n")

with open("sales.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))
print(rows[0])
print(sum(int(r["qty"]) for r in rows))
Output
{'product': 'mug', 'qty': '3'}
8

csv.DictReader turns each row into a dictionary using the header line. Values arrive as text, so convert numbers with int() or float().

Handling errors with try and except

Python
for text in ["42", "4.2", "abc"]:
    try:
        number = int(text)
    except ValueError:
        print(f"{text!r} is not a whole number")
    else:
        print(f"Got {number}")
Output
Got 42
'4.2' is not a whole number
'abc' is not a whole number
  • try holds the code that might fail.
  • except SomeError runs only if that error happens. Catch specific errors, not everything.
  • else runs when no error happened; finally always runs, for clean-up.
Python
try:
    with open("missing.txt", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found — using defaults")
finally:
    print("Done")
Output
File not found — using defaults
Done

Raising your own errors

Python
def set_age(age: int) -> int:
    if age < 0:
        raise ValueError("age can't be negative")
    return age

try:
    set_age(-5)
except ValueError as err:
    print("Problem:", err)
Output
Problem: age can't be negative

Practice

Add up the valid numbers in values = ["10", "x", "5", "", "7"]. Use try / except ValueError to skip anything that isn't a whole number. Print the total, then on a second line how many values were skipped.

Expected output:
22
2
Your code

Quick check

1. Why use with open(...) as f:?

2. What does mode "w" do to an existing file?

3. When does an else block after try/except run?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →