Files and errors
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
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
| Mode | Meaning |
|---|---|
"r" | read (the default) |
"w" | write — creates the file or empties an existing one |
"a" | append to the end |
Reading line by line
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
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
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'}
8csv.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
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
tryholds the code that might fail.except SomeErrorruns only if that error happens. Catch specific errors, not everything.elseruns when no error happened;finallyalways runs, for clean-up.
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
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