Python · Chapter 26 of 45
Python File Handling
Open a file with `open(path, mode)` and always close it — or use `with` which closes automatically.
Modes: `r` read, `w` write (overwrite), `a` append, `b` binary.
with open() as ...
The recommended pattern. Guarantees the file is closed even if an error occurs.
Reading vs writing
`read()` grabs everything; `readlines()` gets a list of lines; iterating a file yields one line at a time (memory-friendly).
Example 1 (python)
with open("hello.txt", "w") as f:
f.write("Hello\nWorld")
with open("hello.txt") as f:
print(f.read())Output
Hello
WorldWrite then read the same file.
Example 2 (python)
with open("data.txt") as f:
for line in f:
print(line.strip())Output
line 1
line 2Iterate line-by-line — memory efficient for big files.
Key points
- `open(path, mode)` returns a file object.
- Use `with` to auto-close.
- Modes: r, w, a, b, x.
- Iterating a file yields lines.
💡 Note: Use encoding="utf-8" explicitly when reading/writing text files — defaults differ across operating systems.
