File Handling and What’s Next
Reading a file
with open("notes.txt", "r") as f:
content = f.read()
print(content)
The with statement automatically closes the file when the block ends, even if an error occurs partway through — always prefer it over calling open() directly and remembering to call .close() yourself, which is easy to forget and can leave files locked or data unwritten.
Reading line by line
with open("notes.txt", "r") as f:
for line in f:
print(line.strip()) # .strip() removes the trailing newline
For large files, reading line by line like this is far more memory-efficient than .read(), which loads the entire file into memory at once — a script processing a multi-gigabyte log file would need this pattern to avoid running out of memory.
Writing to a file
with open("notes.txt", "w") as f:
f.write("Finished the Python course!")
"w" overwrites the file completely if it already exists — use "a" (append) instead to add new content to the end of an existing file without erasing what’s already there.
Working with CSV data
import csv
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])
csv.DictReader reads each row as a dictionary keyed by the column headers in the first line of the file, which is almost always more convenient than working with raw index positions like row[0], row[1].
Handling missing files gracefully
try:
with open("notes.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("That file doesn't exist yet.")
content = ""
Real programs rarely control every detail of their environment — a file might be missing, permissions might be wrong. Wrapping file operations in try/except is the difference between a program that crashes and one that fails gracefully.
Onward to the advanced lessons
You now know variables, control flow, functions, core data structures, classes, and file I/O — enough to build real scripts and read most Python codebases. The next three lessons take you from here to a more professional level: comprehensions, decorators, and working with real APIs.