Python

Binary File Handling Using Pickle, CBSE Class 12 Complete Guide

Learn binary file handling using pickle module in Python for CBSE Class 12. Covers dump, load, EOFError handling with complete programs and output.

Binary file handling is an important topic in the CBSE Class 12 Computer Science syllabus. Unlike text files that store data as human-readable characters, binary files store data in byte format using Python's pickle module. This guide covers everything you need to know for the board exam and practical exam.

What is a Binary File?

A binary file stores data in binary format (sequences of bytes) rather than as human-readable text. When you open a binary file in a text editor, you see garbled characters because the data is not meant to be read directly by humans.

Advantages of binary files over text files:

  • Can store any Python object (lists, dictionaries, class objects), Faster to read and write, Data is more compact (smaller file size), Preserves the exact data type (no need to convert from strings)

The Pickle Module

The pickle module converts Python objects to byte streams (serialization) and byte streams back to Python objects (deserialization).

Operation Method Description
Serialization (Writing) pickle.dump(object, file) Writes a Python object to a binary file
Deserialization (Reading) pickle.load(file) Reads a Python object from a binary file
import pickle

File Opening Modes for Binary Files

Mode Description
"rb" Read binary. File must exist.
"wb" Write binary. Creates new file or overwrites existing.
"ab" Append binary. Creates new file or appends to existing.
"rb+" Read and write binary. File must exist.
"wb+" Write and read binary. Creates new or overwrites.
"ab+" Append and read binary. Creates new or appends.

Program 1: Writing to a Binary File

import pickle

# Data to write
students = [
    {"roll": 1, "name": "Aman", "marks": 85},
    {"roll": 2, "name": "Priya", "marks": 92},
    {"roll": 3, "name": "Rahul", "marks": 78}
]

# Writing to binary file
with open("students.dat", "wb") as f:
    for student in students:
        pickle.dump(student, f)

print("Data written successfully!")
Data written successfully!

Each call to pickle.dump() writes one object to the file. Here we write three dictionaries, one at a time.


Program 2: Reading from a Binary File

To read all objects from a binary file, you keep calling pickle.load() in a loop until an EOFError is raised (which signals the end of the file).

import pickle

with open("students.dat", "rb") as f:
    try:
        while True:
            student = pickle.load(f)
            print(student)
    except EOFError:
        pass
{'roll': 1, 'name': 'Aman', 'marks': 85}
{'roll': 2, 'name': 'Priya', 'marks': 92}
{'roll': 3, 'name': 'Rahul', 'marks': 78}

Important: The try-except EOFError pattern is the standard way to read all objects from a binary file. This is asked in almost every exam.


Program 3: Writing and Reading a List as a Single Object

Instead of writing each item separately, you can write an entire list as one object.

import pickle

# Writing
marks = [85, 92, 78, 95, 67]
with open("marks.dat", "wb") as f:
    pickle.dump(marks, f)

# Reading
with open("marks.dat", "rb") as f:
    data = pickle.load(f)
    print(data)
    print("Average:", sum(data) / len(data))
[85, 92, 78, 95, 67]
Average: 83.4

When you dump an entire list as one object, you only need one pickle.load() call to read it back.


Program 4: Search for a Record in a Binary File

This is one of the most common practical exam questions.

import pickle

def search_student(roll_no):
    found = False
    with open("students.dat", "rb") as f:
        try:
            while True:
                student = pickle.load(f)
                if student["roll"] == roll_no:
                    print("Record Found!")
                    print("Name:", student["name"])
                    print("Marks:", student["marks"])
                    found = True
                    break
        except EOFError:
            pass

    if not found:
        print("Record not found for Roll No:", roll_no)

# Test
search_student(2)
print()
search_student(5)
Record Found!
Name: Priya
Marks: 92

Record not found for Roll No: 5

Program 5: Update a Record in a Binary File

To update a record, read all records into a list, modify the required record, and write all records back.

import pickle

def update_marks(roll_no, new_marks):
    records = []

    # Read all records
    with open("students.dat", "rb") as f:
        try:
            while True:
                records.append(pickle.load(f))
        except EOFError:
            pass

    # Update the matching record
    found = False
    for student in records:
        if student["roll"] == roll_no:
            student["marks"] = new_marks
            found = True
            break

    if found:
        # Write all records back
        with open("students.dat", "wb") as f:
            for student in records:
                pickle.dump(student, f)
        print("Record updated successfully!")
    else:
        print("Record not found!")

update_marks(1, 95)
Record updated successfully!

Program 6: Delete a Record from a Binary File

Similar to update, read all records, exclude the one to delete, and write the rest back.

import pickle

def delete_student(roll_no):
    records = []

    with open("students.dat", "rb") as f:
        try:
            while True:
                records.append(pickle.load(f))
        except EOFError:
            pass

    original_count = len(records)
    records = [s for s in records if s["roll"] != roll_no]

    if len(records) < original_count:
        with open("students.dat", "wb") as f:
            for student in records:
                pickle.dump(student, f)
        print("Record deleted successfully!")
    else:
        print("Record not found!")

delete_student(3)
Record deleted successfully!

Program 7: Count Records in a Binary File

import pickle

def count_records():
    count = 0
    with open("students.dat", "rb") as f:
        try:
            while True:
                pickle.load(f)
                count += 1
        except EOFError:
            pass
    return count

print("Total records:", count_records())
Total records: 2

Program 8: Append Records to an Existing Binary File

Use "ab" mode to add records without overwriting existing data.

import pickle

def add_student(roll, name, marks):
    student = {"roll": roll, "name": name, "marks": marks}
    with open("students.dat", "ab") as f:
        pickle.dump(student, f)
    print("Student added successfully!")

add_student(4, "Neha", 88)
add_student(5, "Vikram", 91)
Student added successfully!
Student added successfully!

Program 9: Display Students with Marks Above a Threshold

import pickle

def display_toppers(threshold):
    print(f"Students with marks above {threshold}:")
    with open("students.dat", "rb") as f:
        try:
            while True:
                student = pickle.load(f)
                if student["marks"] > threshold:
                    print(f"  {student['name']} - {student['marks']}")
        except EOFError:
            pass

display_toppers(85)
Students with marks above 85:
  Aman - 95
  Neha - 88
  Vikram - 91

Common Mistakes to Avoid

Mistake 1: Forgetting to Import Pickle

# Wrong - NameError
pickle.dump(data, f)

# Correct
import pickle
pickle.dump(data, f)

Mistake 2: Opening Binary File in Text Mode

# Wrong - will cause errors
f = open("data.dat", "w")

# Correct
f = open("data.dat", "wb")

Mistake 3: Not Handling EOFError

# Wrong - crashes at end of file
while True:
    data = pickle.load(f)

# Correct
try:
    while True:
        data = pickle.load(f)
except EOFError:
    pass

Mistake 4: Using "wb" Instead of "ab" When Appending

# Wrong - overwrites existing data
f = open("data.dat", "wb")

# Correct - appends to existing data
f = open("data.dat", "ab")

Key Differences: Text File vs Binary File

Feature Text File Binary File
Data format Human-readable characters Byte stream
Extension .txt, .csv .dat, .bin
Read/Write read(), write() pickle.load(), pickle.dump()
Data types Everything stored as string Preserves original data type
Mode "r", "w", "a" "rb", "wb", "ab"
EOL character \n is translated No translation
Speed Slower Faster
Module needed None pickle

Exam Tips

  1. Always import pickle at the top of your program.
  2. Always use binary mode ("rb", "wb", "ab") when working with pickle.
  3. Always handle EOFError when reading from a binary file.
  4. The dump-load cycle is the heart of binary file handling, practice it until it becomes second nature.
  5. For update and delete operations, the pattern is: read all into a list, modify, write all back.
  6. Remember that pickle.dump() writes one object per call, and pickle.load() reads one object per call.

Binary file handling with pickle is a guaranteed question in both the theory and practical exam. Master these programs and you will be well prepared.

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube