Definition
How does a program remember data after it closes?
A file stores data on disk so that it outlives the program. open() opens a file in a mode: "r" to read, "w" to write (replacing what was there) and "a" to append. The with statement closes the file automatically. The csv module reads and writes comma-separated files, the usual format for tables of data.
In simple words
Variables vanish when a program ends. Writing to a file is like writing in a notebook you can open tomorrow. with open("notes.txt", "w") as f: f.write("Hello") saves it; with open("notes.txt") as f: f.read() brings it back. A CSV file is a spreadsheet saved as plain text.
Why it matters
Almost every AI project starts by reading data from files, usually CSV, and ends by saving results, models or reports. Doing it safely, with with and the right mode, prevents lost data.
How it works
| Mode | Meaning | If the file exists |
|---|---|---|
| "r" | Read (the default) | Read it |
| "w" | Write | Erase it and start fresh |
| "a" | Append | Add to the end |
In code
Saving an attendance register as a CSV file, reading it back, and appending a line to a log.
import csv
register = [["name", "present"], ["Aarav", "yes"], ["Meera", "no"], ["Kabir", "yes"]]
with open("attendance.csv", "w", newline="") as f:
csv.writer(f).writerows(register)
with open("attendance.csv") as f:
rows = list(csv.DictReader(f))
present = [row["name"] for row in rows if row["present"] == "yes"]
print("Rows read:", len(rows))
print("Present:", present)
with open("log.txt", "w") as f:
f.write("Register saved")
with open("log.txt", "a") as f:
f.write(" and checked")
with open("log.txt") as f:
print("Log says:", f.read())Output
Rows read: 3 Present: ['Aarav', 'Kabir'] Log says: Register saved and checked
Try it yourself
Which mode?
Match each job to the file mode it needs.
- Load yesterday's saved scores
- Start a brand-new report, replacing the old one
- Add today's entry to the end of a diary
Common mistakes
- Opening with "w" when you meant "a", and losing everything.
- Forgetting to close a file. Use with and it's done for you.
- Treating CSV numbers as numbers. They are read as text; convert with int() or float().
Check yourself
Summary
- Files keep data after the program ends.
- Modes: r reads, w replaces, a appends; with closes the file.
- csv reads and writes tables; convert text to numbers yourself.
Finished reading?