Python File Handling
| Mode | Meaning |
|---|---|
| "r" | Read (default); error if file is missing |
| "w" | Write; creates or overwrites the file |
| "a" | Append to the end of the file |
| "x" | Create; error if the file exists |
| "b" / "t" | Binary / text (combine, e.g. "rb") |
with open("notes.txt", "w") as f: # 'with' closes the file automatically
f.write("Line 1\nLine 2\n")
with open("notes.txt", "a") as f:
f.write("Line 3\n")
with open("notes.txt") as f:
for no, line in enumerate(f, 1):
print(no, line.strip())
1 Line 1
2 Line 2
3 Line 3
Reading a CSV File
import csv
with open("marks.csv") as f:
for row in csv.DictReader(f):
print(row["name"], row["marks"])
Asha 88
Ravi 76
Track your progress through the Python course