Open with with
with open("notes.txt", "r", encoding="utf-8") as f: — the file closes automatically when the block ends, even after errors.
Modes
| Mode | Meaning |
|---|---|
r |
read (default) |
w |
write — erases the file first |
a |
append to the end |
x |
create; error if it exists |
b |
binary, e.g. rb for images |
Reading
f.read(), f.readline(), f.readlines(), or loop for line in f: (best for big files).
Writing
f.write("text\n") — add \n yourself. f.writelines(list).
Always pass encoding="utf-8" for text, especially on Windows.
CSV files
csv.reader, csv.writer, and the friendlier csv.DictReader / csv.DictWriter. Open CSV files with newline="".
pathlib
from pathlib import Path — Path("data") / "report.txt", .exists(), .read_text(), .write_text(), .mkdir(parents=True, exist_ok=True), .glob("*.csv").
Example
import csv
from pathlib import Path
folder = Path("data")
folder.mkdir(exist_ok=True)
file = folder / "students.csv"
students = [
{"name": "Asha", "course": "BCA", "marks": 88},
{"name": "Ravi", "course": "MCA", "marks": 64},
]
with open(file, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "course", "marks"])
writer.writeheader()
writer.writerows(students)
with open(file, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(f"{row['name']:<6} {row['course']:<4} {row['marks']}")
log = folder / "log.txt"
with open(log, "a", encoding="utf-8") as f:
f.write("Report generated\n")
print(log.read_text(encoding="utf-8"))
Creates data/students.csv, prints each student on a line (Asha BCA 88, Ravi MCA 64), and appends a line to data/log.txt each time it runs.