So far our programs forget everything the moment they stop — variables live only in memory. File handling gives programs data persistence: the ability to save data to disk and read it back later. This is how real apps remember your settings, scores and records. CBSE expects three flavours: text files, binary files (with pickle), and CSV files.
1Text files: open, read, write, with
Files come in two kinds: text files (human-readable characters, e.g. .txt) and binary files (raw bytes, e.g. images). You work with a file in three steps: open it, process it, then close it.
Opening: the access modes
| Mode | Meaning |
|---|---|
r | Read (default). Error if the file is missing. |
w | Write — creates the file, or erases existing contents. |
a | Append — adds to the end, keeps existing contents. |
r+ / w+ / a+ | Read and write together. |
f = open("notes.txt", "w")
f.write("Hello Vidaara\n")
f.close() # always close!The with statement (best practice)
The with statement opens a file and closes it automatically, even if an error occurs — so you never forget:
with open("notes.txt", "r") as f:
data = f.read() # whole file as one string
# file is closed automatically hereReading and writing
read()— the whole file as a string;read(n)— n characters.readline()— one line;readlines()— a list of all lines.write(s)— write a string;writelines(list)— write a list of strings.tell()— current file-pointer position;seek(n)— move the pointer to byte n.
w erases the file's contents! Use a (append) when you want to keep what's already there.- Steps: open → process → close. The
withstatement closes the file automatically. - Modes: r (read), w (write, erases!), a (append), and the + variants for read+write.
- Read: read(), readline(), readlines(). Write: write(), writelines(). Pointer: tell(), seek().
2Binary files with pickle
Binary files store raw bytes, not text — useful for saving whole Python objects (lists, dictionaries) directly. The pickle module does this through serialization: turning an object into a byte stream (pickling) and back (unpickling).
pickle.dump(object, file)— write (pickle) an object into a binary file.pickle.load(file)— read (unpickle) an object back from a binary file.
Binary files must be opened in binary modes: rb (read binary), wb (write binary), ab (append binary):
import pickle
student = {"name": "Asha", "marks": 92}
# write (pickle) the dictionary
with open("data.dat", "wb") as f:
pickle.dump(student, f)
# read (unpickle) it back
with open("data.dat", "rb") as f:
record = pickle.load(f)
print(record["name"]) # Ashaload the records into a list, change the list in memory, then dump the whole list back.- Binary files store raw bytes;
pickleserialises whole Python objects (lists, dicts). pickle.dump(obj, f)writes (pickles);pickle.load(f)reads (unpickles).- Open binary files with
rb/wb/ab. - Insert/search/update/delete records by loading them, changing the list, and dumping it back.
3CSV files
CSV (Comma-Separated Values) is a simple text format where each line is a row and values are separated by commas — the universal language of spreadsheets. Python's csv module handles it cleanly:
import csv
# WRITING
with open("marks.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Marks"]) # one row
writer.writerows([["Asha", 92], ["Ravi", 85]]) # many rows
# READING
with open("marks.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row) # each row is a list of stringscsv.writer(f)→writerow(list)writes one row;writerows(list_of_lists)writes many.csv.reader(f)→ loop over it to get each row as a list of strings.- You can change the separator with the
delimiterargument (e.g. a tab or semicolon).
newline="" when opening a CSV for writing, to avoid blank lines appearing between rows on some systems.- CSV is plain text: rows on lines, values separated by commas — used by spreadsheets.
- Writing:
csv.writer(f)withwriterow()(one row) andwriterows()(many). - Reading:
csv.reader(f), looped to give each row as a list of strings. - Open CSVs for writing with
newline=""to avoid extra blank lines.
★ Practical: a notes saver (run on a computer)
On a real Python install (IDLE/Thonny), write programs that:
- Use
with open(..."w")to write three lines to notes.txt, then read them back with readlines(). - Append a fourth line using mode 'a' and confirm the first three survive.
- Pickle a dictionary of marks to a .dat file, then unpickle and print it.
- Write a CSV of three students with writerows(), then read and print each row.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.