Study Guide
Complete Guide to File Handling in Python, CBSE Class 12
Learn file handling in Python for CBSE Class 12. Text files, binary files, CSV files with pickle and csv module. All modes, methods, and examples.
File handling is the most important chapter in CBSE Class 12 Computer Science. It carries 6-8 marks in the board exam and is also a major part of the practical exam. This guide covers everything you need to know.
Why File Handling?
Programs store data in variables, which are lost when the program ends. Files let you store data permanently on disk. Python can work with three types of files:
- Text files - Store data as readable characters (.txt)
- Binary files - Store data in binary format (.dat)
- CSV files - Store tabular data as comma-separated values (.csv)
File Modes
| Mode | Description | File Exists? | File Doesn't Exist? |
|---|---|---|---|
r |
Read only (default) | Opens file | Error |
w |
Write only | Overwrites file | Creates new file |
a |
Append only | Adds to end | Creates new file |
r+ |
Read and write | Opens file | Error |
w+ |
Write and read | Overwrites file | Creates new file |
a+ |
Append and read | Adds to end | Creates new file |
rb |
Read binary | Opens file | Error |
wb |
Write binary | Overwrites file | Creates new file |
ab |
Append binary | Adds to end | Creates new file |
Exam tip: The most commonly asked modes are r, w, a, rb, and wb. Know what happens when the file does not exist for each mode.
Part 1: Text File Handling
Opening and Closing Files
# Method 1: Manual open and close
f = open("data.txt", "r")
content = f.read()
f.close()
# Method 2: Using 'with' statement (recommended)
with open("data.txt", "r") as f:
content = f.read()
# File automatically closes when the block ends
Always prefer the with statement. It automatically closes the file even if an error occurs. The examiner appreciates this.
Writing to a Text File
# write() - writes a string
f = open("output.txt", "w")
f.write("Hello World\n")
f.write("Python is fun\n")
f.close()
# writelines() - writes a list of strings
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
f = open("output.txt", "w")
f.writelines(lines)
f.close()
Important: write() does not add \n automatically. You must add it yourself. writelines() does not add \n between items either.
Reading from a Text File
Assume data.txt contains:
Hello World
Python is fun
CBSE Class 12
read(), Read Entire File
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
Hello World
Python is fun
CBSE Class 12
read(n), Read n Characters
f = open("data.txt", "r")
content = f.read(5)
print(content)
f.close()
Hello
readline(), Read One Line
f = open("data.txt", "r")
line1 = f.readline()
line2 = f.readline()
print(line1, end="")
print(line2, end="")
f.close()
Hello World
Python is fun
Each call to readline() reads the next line. The newline character \n is included in the returned string.
readlines(), Read All Lines as a List
f = open("data.txt", "r")
lines = f.readlines()
print(lines)
f.close()
['Hello World\n', 'Python is fun\n', 'CBSE Class 12\n']
Reading Line by Line Using a Loop
f = open("data.txt", "r")
for line in f:
print(line, end="")
f.close()
This is the most memory-efficient way to read a file.
Appending to a File
f = open("data.txt", "a")
f.write("New line added\n")
f.close()
This adds data at the end without deleting existing content.
File Pointer, tell() and seek()
f = open("data.txt", "r")
print(f.tell()) # 0 (beginning of file)
f.read(5)
print(f.tell()) # 5 (after reading 5 characters)
f.seek(0) # Move pointer back to beginning
print(f.tell()) # 0
f.close()
tell()returns the current position of the file pointerseek(offset)moves the file pointer to a given position
Part 2: Binary File Handling with Pickle
Binary files store data in a format that is not human-readable but is efficient for Python objects. The pickle module converts Python objects to binary (serialization) and back (deserialization).
- pickle.dump() - Write an object to a binary file (serialization/pickling)
- pickle.load() - Read an object from a binary file (deserialization/unpickling)
Writing to a Binary File
import pickle
student = {"rollno": 1, "name": "Aman", "marks": 85}
f = open("student.dat", "wb")
pickle.dump(student, f)
f.close()
print("Data written successfully")
Reading from a Binary File
import pickle
f = open("student.dat", "rb")
student = pickle.load(f)
print(student)
f.close()
{'rollno': 1, 'name': 'Aman', 'marks': 85}
Writing Multiple Records
import pickle
f = open("students.dat", "wb")
for i in range(3):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
record = [roll, name, marks]
pickle.dump(record, f)
f.close()
Reading Multiple Records
import pickle
f = open("students.dat", "rb")
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
pass
f.close()
Important: When reading multiple records from a binary file, you must use a try-except block to catch EOFError. This tells Python to stop reading when the file ends. This pattern is asked in almost every board exam.
Searching in a Binary File
import pickle
def search_student(rollno):
f = open("students.dat", "rb")
found = False
try:
while True:
record = pickle.load(f)
if record[0] == rollno:
print("Found:", record)
found = True
break
except EOFError:
pass
if not found:
print("Record not found")
f.close()
search_student(2)
Updating a Record in a Binary File
import pickle
def update_marks(rollno, new_marks):
f = open("students.dat", "rb")
records = []
try:
while True:
record = pickle.load(f)
if record[0] == rollno:
record[2] = new_marks
records.append(record)
except EOFError:
pass
f.close()
f = open("students.dat", "wb")
for record in records:
pickle.dump(record, f)
f.close()
print("Record updated")
update_marks(1, 95)
Part 3: CSV File Handling
CSV (Comma-Separated Values) files store tabular data in plain text format. Python uses the csv module for CSV file operations.
Writing to a CSV File
import csv
f = open("students.csv", "w", newline="")
writer = csv.writer(f)
writer.writerow(["RollNo", "Name", "Marks"]) # Header row
writer.writerow([1, "Aman", 85])
writer.writerow([2, "Priya", 92])
writer.writerow([3, "Rahul", 67])
f.close()
Important: Always pass newline="" when opening a CSV file for writing. Without it, extra blank lines appear between rows on Windows.
Reading from a CSV File
import csv
f = open("students.csv", "r")
reader = csv.reader(f)
for row in reader:
print(row)
f.close()
['RollNo', 'Name', 'Marks']
['1', 'Aman', '85']
['2', 'Priya', '92']
['3', 'Rahul', '67']
Note: CSV reader returns all values as strings, even numbers.
Writing Multiple Rows at Once
import csv
data = [
["RollNo", "Name", "Marks"],
[1, "Aman", 85],
[2, "Priya", 92]
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
Common Mistakes to Avoid
-
Forgetting to close the file. Use the
withstatement to avoid this. -
Using
wmode when you meanamode. Thewmode overwrites the entire file. Useato add data at the end. -
Not handling EOFError in binary files. Always use
try-except EOFErrorwhen reading multiple records with pickle. -
Forgetting
newline=""in CSV. This causes blank lines on Windows. -
Reading a file opened in write mode. If you open a file in
wmode, you cannot read from it. User+orw+if you need both. -
Not importing pickle or csv. Write
import pickleorimport csvat the top. -
Confusing
write()andwritelines().write()takes a single string.writelines()takes a list of strings. Neither adds\nautomatically.
Quick Revision Table
| Operation | Text File | Binary File | CSV File |
|---|---|---|---|
| Module | Built-in | pickle |
csv |
| Open mode | r, w, a |
rb, wb, ab |
r, w |
| Write | write(), writelines() |
pickle.dump() |
writer.writerow() |
| Read | read(), readline(), readlines() |
pickle.load() |
csv.reader() |
| Data format | Human-readable | Binary (not readable) | Comma-separated |
| Extension | .txt |
.dat |
.csv |
Exam-Style Question
Q: Write a function to count the number of lines in a text file "poem.txt" that start with an uppercase letter.
def count_upper_lines():
count = 0
with open("poem.txt", "r") as f:
for line in f:
if line[0].isupper():
count += 1
return count
print("Lines starting with uppercase:", count_upper_lines())
This is the level of question expected in the board exam. Practice writing complete functions with proper file open, read, and close operations.
Want to learn more?
Explore free chapter-wise notes with quizzes and code playground
Prefer watching over reading?
Subscribe for free.