Lesson 31 / 47
Reading & Writing Files
Open, read, write and close text files, safely with `with`.
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.