Programs need to read and write files — configs, data, logs, reports. Python does this with open(), and the golden rule is to wrap it in a with block so the file is closed automatically, even if an error occurs partway through.
The with statement
# Write (creates or overwrites)with open("notes.txt", "w") as f:f.write("first line\n")f.write("second line\n")# Read the whole filewith open("notes.txt") as f:text = f.read()# Iterate line by line — memory-efficient for big fileswith open("notes.txt") as f:for line in f:print(line.strip()) # strip the trailing newline
File modes
| Mode | Meaning |
|---|---|
"r" | Read (default) — errors if the file is missing |
"w" | Write — creates or OVERWRITES |
"a" | Append — adds to the end |
"x" | Create — errors if it already exists |
"rb" / "wb" | Binary read/write (images, pickles) |
A note on paths
For anything beyond a quick script, use pathlib for clean, cross-platform paths:
from pathlib import Pathp = Path("data") / "notes.txt" # OS-correct path joiningp.read_text() # shortcut to readp.write_text("hello") # shortcut to writep.exists() # True/False
Key takeaways
- 01open(path, mode) opens a file; a with block closes it automatically.
- 02Modes: r read, w overwrite, a append, x create, add b for binary.
- 03"w" overwrites silently — use "a" to append without data loss.
- 04Iterate line by line for large files; .read() loads it all at once.
- 05Use pathlib.Path for clean, cross-platform path handling.
