I1 · Python Programming for AI

Reading and Writing Files

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.

10 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

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

ModeMeaningIf the file exists
"r"Read (the default)Read it
"w"WriteErase it and start fresh
"a"AppendAdd to the end

In code

Saving an attendance register as a CSV file, reading it back, and appending a line to a log.

attendance.py
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

Question 1

1. Which mode adds to the end of a file?

Question 2

2. Why use with open(...)?

Question 3

3. Values read from a CSV file arrive as…

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?

Sources: Python docs: Reading and Writing Files