Unit 1: Computational Thinking & Programming - 2
Chapter 2: File Handling - Text, Binary & CSV
1. Why File Handling?
Variables and data structures in a running program live in RAM (volatile memory) - they vanish the moment the program ends. A file stores data on a non-volatile storage device (hard disk/SSD), so data persists even after the program closes, and can be reused later or shared with other programs.
Types of Files
| Type | Description | Examples |
|---|---|---|
| Text File | Stores data as a sequence of human-readable characters (ASCII/Unicode), usually organized into lines | .txt, .csv, .py |
| Binary File | Stores data in the same binary format used internally by the program (0s and 1s), not directly human-readable | .dat, .bin, images |
2. Opening and Closing a File
file_object = open(filename, mode)
# ... operations ...
file_object.close()
Common File Access Modes
| Mode | Meaning |
|---|---|
'r' |
Read (default). Error if file does not exist. |
'w' |
Write. Creates a new file, overwrites if it already exists. |
'a' |
Append. Creates file if it doesn't exist; adds data to the end without erasing existing content. |
'r+' |
Read and Write. File must already exist. |
'rb', 'wb', 'ab' |
Same as above, but in binary mode. |
The with Statement (Recommended)
Using with automatically closes the file, even if an error occurs inside the block - so you never need to call .close() explicitly.
with open("marks.txt", "r") as f:
data = f.read()
# file is auto-closed here, as soon as the block ends
3. Reading and Writing Text Files
| Method | Purpose |
|---|---|
read(n) |
Reads n characters; reads the whole file if n is omitted |
readline() |
Reads a single line (including the \n) |
readlines() |
Reads all lines and returns them as a list of strings |
write(string) |
Writes a string to the file (no newline added automatically) |
writelines(list) |
Writes a list of strings to the file |
# Writing to a text file
with open("students.txt", "w") as f:
f.write("Amit,78\n")
f.write("Priya,92\n")
# Reading line by line
with open("students.txt", "r") as f:
for line in f:
name, marks = line.strip().split(",")
print(name, "scored", marks)
The File Pointer: tell() and seek()
tell()returns the current byte position of the file pointer.seek(offset)moves the file pointer to a specific byte position (commonly used to go back to the start:seek(0)).
f = open("data.txt", "r")
print(f.tell()) # 0 (pointer at the start)
f.read(5)
print(f.tell()) # 5 (pointer moved after reading 5 characters)
f.seek(0) # move back to the beginning
4. Binary Files and the pickle Module
Binary files store Python objects (lists, dictionaries, tuples) directly in their internal binary representation - there's no need to convert them to strings and parse them back, as you would with text files. This is done through serialization (pickling).
| Function | Purpose |
|---|---|
pickle.dump(object, file) |
Serializes object and writes it to the binary file |
pickle.load(file) |
Reads and de-serializes the next object from the binary file |
import pickle
# Writing records to a binary file
student = {"name": "Kabir", "marks": 88}
with open("student.dat", "wb") as f:
pickle.dump(student, f)
# Reading a single record back
with open("student.dat", "rb") as f:
data = pickle.load(f)
print(data) # {'name': 'Kabir', 'marks': 88}
Reading Multiple Records Until End-of-File
Since a binary file doesn't signal "end of file" the way text files do, pickle.load() raises an EOFError once there is nothing left to read. The standard board-exam pattern wraps this in a loop with try/except:
import pickle
records = [{"name": "Kabir", "marks": 88}, {"name": "Isha", "marks": 95}]
with open("students.dat", "wb") as f:
for rec in records:
pickle.dump(rec, f) # each dump() call appends one object
with open("students.dat", "rb") as f:
while True:
try:
rec = pickle.load(f)
print(rec)
except EOFError:
break # reached the end of the file, stop looping
5. CSV (Comma Separated Values) Files
CSV is a plain text format where each line is a data record, and fields within a record are separated by a comma (or another delimiter). Python's built-in csv module handles the quoting/escaping details for us.
| Function | Purpose |
|---|---|
csv.writer(file) |
Returns a writer object |
writer.writerow(list) |
Writes a single row |
writer.writerows(list_of_lists) |
Writes multiple rows at once |
csv.reader(file) |
Returns a reader object that iterates row by row, each row as a list of strings |
import csv
# Writing a CSV file
with open("marks.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Subject", "Marks"]) # header row
writer.writerows([["Amit", "CS", 92], ["Priya", "CS", 88]])
# Reading a CSV file
with open("marks.csv", "r", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row) # each row is printed as a list, e.g. ['Amit', 'CS', '92']
newline=""is recommended when opening files forcsvmodule operations on Windows, to prevent extra blank lines from being inserted between rows.
6. Board Exam Focus Questions
Q1. Write a function count_lines() that counts and returns the number of lines present in a text file "story.txt".
def count_lines():
count = 0
with open("story.txt", "r") as f:
for line in f:
count += 1
return count
Q2. Write a function search_record(empno) that reads a binary file "emp.dat" (containing dictionaries with keys 'eno' and 'name') and displays the record whose employee number matches empno.
import pickle
def search_record(empno):
found = False
with open("emp.dat", "rb") as f:
while True:
try:
rec = pickle.load(f)
if rec["eno"] == empno:
print(rec)
found = True
except EOFError:
break
if not found:
print("Record not found.")
Q3. Differentiate between the r+ mode and the w mode of opening a file.
Answer: r+ opens an existing file for both reading and writing without deleting its content (raises an error if the file doesn't exist). w mode always creates a fresh, empty file for writing - if a file with the same name already exists, its entire previous content is erased.