Lesson 33 / 49
Reading & Writing Files
Read and write text files safely with the with statement, line by line for large files, and learn context managers.
The with statement
with open(...) as f: opens a file and guarantees it closes, even if an error happens inside the block.
with open("notes.txt", "w") as f:
f.write("Hello, file!\n")
with open("notes.txt", "r") as f:
content = f.read()
print(content)Reading line by line
Reading line by line keeps memory low for large files, since the file object is itself iterable.
with open("notes.txt") as f:
for line in f:
print(line.strip())Context managers
with works because file objects are context managers — they define __enter__/__exit__ so setup and cleanup happen automatically.