Class XII · Chapter 2Unit 1, Computational Thinking and Programming, 2 (40 marks)8 min read
Chapter 2: File Handling in Python
CBSE Unit: Unit 1, Computational Thinking and Programming, 2 (40 marks) Marks Weightage: ~12-15 marks (HIGHEST weightage chapter in the entire exam) Priority: CRITICAL, most programs asked from this chapter
Key Concepts
2.1 What is a File?
- A named location on secondary storage where data is permanently stored, Variables lose data when program ends; files persist data, Two main types: Text files and Binary files
2.2 Types of Files
| Feature | Text File | Binary File |
|---|---|---|
| Content | Human-readable characters | Non-human readable bytes |
| Extensions | .txt, .py, .csv, .html | .dat, .jpg, .mp3, .exe |
| Storage | ASCII/Unicode values of characters | Actual content as bytes |
| EOL | Each line terminated by \n |
No line terminator concept |
| Readability | Can open in any text editor | Need specific software |
| Separators | Whitespace, comma, tab | Not applicable |
2.3 Opening a File
file_object = open(file_name, access_mode)
- Returns a file handle (file object), If file doesn't exist in write/append mode → creates new file, If file doesn't exist in read mode → raises error
File object attributes:
file.closed→ True if file is closedfile.mode→ access mode usedfile.name→ name of the file
File Access Modes (MUST MEMORIZE)
| Mode | Description | File Pointer | Creates new? | Overwrites? |
|---|---|---|---|---|
r |
Read only | Beginning | No (error if missing) | No |
rb |
Read binary | Beginning | No | No |
r+ |
Read + Write | Beginning | No | No |
w |
Write only | Beginning | Yes | YES, erases all |
wb+ |
Write + Read binary | Beginning | Yes | YES |
a |
Append | End | Yes | No, adds at end |
a+ |
Append + Read | End | Yes | No |
Critical difference: w mode DESTROYS existing content. a mode PRESERVES it.
2.4 Closing a File
file_object.close()
- Frees memory, flushes buffer to disk, Always close files after use, Re-assigning file object auto-closes previous file
2.5 Opening with with clause (RECOMMENDED)
with open("myfile.txt", "r+") as myObject:
content = myObject.read()
# File automatically closed here - no need for close()
Advantage: Auto-closes even if exception occurs. Simpler syntax.
Writing to Text Files
write() method
file_object.write(string)
- Writes a single string, Returns number of characters written, Must add
\nmanually for new lines, Numeric data must be converted to string first:write(str(marks))
f = open("myfile.txt", "w")
f.write("Hello World\n") # Returns 12
f.write(str(58)) # Returns 2 (writes "58")
f.close()
writelines() method
file_object.writelines(list_of_strings)
- Writes multiple strings from a list/tuple, Does NOT add
\nautomatically, Does NOT return character count
lines = ["Hello everyone\n", "Writing multiline\n", "Third line"]
f = open("myfile.txt", "w")
f.writelines(lines)
f.close()
Reading from Text Files
read([n]) method
content = file_object.read(n) # reads n bytes
content = file_object.read() # reads ENTIRE file
readline([n]) method
line = file_object.readline() # reads ONE complete line (including \n)
partial = file_object.readline(10) # reads max 10 chars or till \n
- Returns empty string at EOF, Use in loop to read file line by line
readlines() method
lines = file_object.readlines() # returns LIST of all lines
# ['Hello everyone\n', 'Writing multiline\n', 'Third line']
Reading with loop (most common)
f = open("myfile.txt", "r")
for line in f:
print(line)
f.close()
split() vs splitlines()
# split() - splits a line into words
"Hello World".split() # ['Hello', 'World']
# splitlines() - keeps the line as one element
"Hello World".splitlines() # ['Hello World']
Setting Offsets: tell() and seek()
tell()
position = file_object.tell() # returns current byte position from beginning
seek(offset, reference_point)
file_object.seek(offset, reference_point)
reference_point: 0 = beginning (default), 1 = current, 2 = endoffset: number of bytes to move
f = open("testfile.txt", "r+")
f.read()
print(f.tell()) # position at end
f.seek(0) # go back to beginning
f.seek(10) # go to 10th byte from beginning
Note: For text files, only seek(0) and seek(0, 0) (beginning) work reliably. Arbitrary seeking works in binary mode.
Binary Files with Pickle Module
What is Pickling?
- Serialization (pickling): converting Python object → byte stream for storage
- Deserialization (unpickling): converting byte stream → Python object
import pickleis required
dump(), write object to binary file
import pickle
pickle.dump(data_object, file_object)
import pickle
data = [1, "Geetika", 'F', 26]
f = open("mybinary.dat", "wb")
pickle.dump(data, f)
f.close()
load(), read object from binary file
import pickle
store_object = pickle.load(file_object)
import pickle
f = open("mybinary.dat", "rb")
data = pickle.load(f)
f.close()
print(data) # [1, 'Geetika', 'F', 26]
Reading ALL records from binary file (handle EOFError)
import pickle
try:
with open("empfile.dat", "rb") as f:
while True:
record = pickle.load(f)
print(record)
except EOFError:
pass
Critical: Always use try-except EOFError when reading binary files in a loop.
CSV Files (from CBSE syllabus, brief in NCERT)
import csv
# Writing
with open("data.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"]) # single row
writer.writerows([["A", 1], ["B", 2]]) # multiple rows
# Reading
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Important Programs for Board Exam
Program 1: Write and read text file
f = open("testfile.txt", "w")
sentence = input("Enter text: ")
f.write(sentence)
f.close()
f = open("testfile.txt", "r")
for line in f:
print(line)
f.close()
Program 2: Read text file, display words separated by
f = open("story.txt", "r")
for line in f:
words = line.split()
for w in words:
print(w + "#", end="")
print()
f.close()
Program 3: Count vowels/consonants/upper/lower in file
f = open("story.txt", "r")
v = c = u = l = 0
data = f.read()
for ch in data:
if ch.isalpha():
if ch.lower() in 'aeiou':
v += 1
else:
c += 1
if ch.isupper():
u += 1
else:
l += 1
f.close()
print(f"Vowels: {v}, Consonants: {c}, Upper: {u}, Lower: {l}")
Program 4: Binary file, write and search student records
import pickle
# Write
f = open("students.dat", "wb")
while True:
roll = int(input("Roll: "))
name = input("Name: ")
pickle.dump([roll, name], f)
if input("More? (y/n): ") == 'n':
break
f.close()
# Search
f = open("students.dat", "rb")
search = int(input("Enter roll to search: "))
found = False
try:
while True:
rec = pickle.load(f)
if rec[0] == search:
print("Found:", rec[1])
found = True
except EOFError:
pass
if not found:
print("Record not found")
f.close()
Program 5: Binary file, update marks
import pickle
f = open("students.dat", "rb")
records = []
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
f.close()
roll = int(input("Enter roll to update: "))
for rec in records:
if rec[0] == roll:
rec[2] = int(input("Enter new marks: "))
f = open("students.dat", "wb")
for rec in records:
pickle.dump(rec, f)
f.close()
Common Board Exam Question Patterns
- MCQ: What is the output of read()/readline()? (1 mark)
- MCQ: Which mode opens file at end/beginning? (1 mark)
- MCQ: Difference between w and a mode? (1 mark)
- Short answer: Differentiate text file vs binary file (2 marks)
- Short answer: Differentiate read/readline/readlines (2 marks)
- Short answer: Differentiate write vs writelines (2 marks)
- Program: Read text file, count/search/display (3-4 marks)
- Program: Binary file, write/search/update/delete records (4-5 marks)
- Program: CSV file, create and read (3 marks)
- Explain: Pickling and unpickling (2-3 marks)
Key Points Students Miss
write()does NOT add\n- you must add it manuallywritelines()does NOT add\nbetween stringswmode DESTROYS existing file content, most common mistakeread()with no argument reads ENTIRE file, file pointer moves to end- After
read(), mustseek(0)to read again from beginning - Binary file reading MUST use
try-except EOFError- no other way to detect end withclause auto-closes file, no need forclose()\ncounts as ONE character in length calculationsreadline()includes\nin the returned stringpickle.dump()needswbmode,pickle.load()needsrbmode
Prefer watching over reading?
Subscribe for free.