Computer Science

Binary File Handling in Python Class 12 CBSE (083): Complete Notes with Pickle Module and File Operations

Class 12 · Computer Science

Binary File Handling in Python (CBSE Class 12 Computer Science - 083)

Binary files store data in binary format (0s and 1s). Unlike text files, the contents of a binary file are not human-readable. Python uses the pickle module to store and retrieve Python objects such as lists, dictionaries, tuples, and user-defined records in binary files.

Learning Objectives

  • Understand binary files.
  • Differentiate between text and binary files.
  • Learn binary file opening modes.
  • Use the pickle module.
  • Understand dump() and load().
  • Perform write, read, search, append, and update operations.

What is a Binary File?

A binary file stores information in binary format. The data is stored exactly as it is represented in computer memory, making binary files faster and more compact than text files.

Examples: student.dat, employee.dat, marks.dat

Text File vs Binary File

Text File Binary File
Stores readable characters. Stores data in binary format.
Human-readable. Not human-readable.
Generally slower. Generally faster.
Suitable for text data. Suitable for structured Python objects.

Opening a Binary File

Python uses the open() function to open a binary file. Binary modes include the letter b.

Syntax


file = open("student.dat","rb")

Binary File Opening Modes

Mode Description File Must Exist?
rb Read Binary Yes
rb+ Read and Write Binary Yes
wb Write Binary (creates new file or overwrites existing file) No
wb+ Read and Write Binary (overwrites existing file) No
ab Append Binary No
ab+ Read and Append Binary No

Closing a Binary File

After performing file operations, always close the binary file to release system resources.

Syntax


file.close()

The Pickle Module

The pickle module is used to convert Python objects into binary format and store them in a binary file. It can also retrieve those objects from the file.

Importing the Module


import pickle

Important Methods of Pickle

Method Purpose
dump() Writes a Python object to a binary file.
load() Reads a Python object from a binary file.

Writing Data Using dump()

The dump() method stores a Python object into a binary file.

Syntax


pickle.dump(object,file)

Example


import pickle

file = open("student.dat","wb")

student = [101,"Riya",89]

pickle.dump(student,file)

file.close()

Reading Data Using load()

The load() method retrieves one object at a time from a binary file.

Syntax


object = pickle.load(file)

Example


import pickle

file = open("student.dat","rb")

record = pickle.load(file)

print(record)

file.close()

Output


[101, 'Riya', 89]

Creating (Writing) Records in a Binary File

Multiple records can be stored by repeatedly calling the dump() method.

Example


import pickle

file = open("student.dat","wb")

while True:

    roll = int(input("Roll No : "))
    name = input("Name : ")
    marks = int(input("Marks : "))

    record = [roll,name,marks]

    pickle.dump(record,file)

    choice = input("Add More (Y/N): ")

    if choice.upper() != "Y":
        break

file.close()

Reading All Records from a Binary File

Since multiple objects are stored one after another, Python reads them until the end of the file is reached.

Example


import pickle

file = open("student.dat","rb")

try:

    while True:

        record = pickle.load(file)

        print(record)

except EOFError:

    file.close()

Searching a Record in a Binary File

Searching is performed by reading each record one by one and comparing the required field.

Example


import pickle

file = open("student.dat","rb")

roll = int(input("Enter Roll Number : "))

found = False

try:

    while True:

        record = pickle.load(file)

        if record[0] == roll:

            print(record)

            found = True

            break

except EOFError:

    pass

if not found:

    print("Record Not Found")

file.close()

Appending Records to a Binary File

New records can be added without deleting existing records by opening the file in append mode.

Example


import pickle

file = open("student.dat","ab")

record = [104,"Rahul",92]

pickle.dump(record,file)

file.close()

Updating a Record in a Binary File

Binary files cannot be modified directly. The common approach is to read each record, modify the required record, store all records temporarily, and rewrite them to the file.

Algorithm

  1. Open the binary file in read mode.
  2. Read each record using load().
  3. Modify the required record.
  4. Store all records in a temporary list.
  5. Open the file in write mode.
  6. Write all records back using dump().

Example


import pickle

records = []

file = open("student.dat","rb")

try:

    while True:

        record = pickle.load(file)

        if record[0] == 101:

            record[2] = 95

        records.append(record)

except EOFError:

    file.close()

file = open("student.dat","wb")

for rec in records:

    pickle.dump(rec,file)

file.close()

Common File Operations Summary

Operation Method Used
Create / Write pickle.dump()
Read pickle.load()
Search Read each record and compare.
Append Open file in ab mode and use dump().
Update Read, modify, and rewrite all records.

Common Programming Errors

  • Forgetting to import the pickle module.
  • Opening a binary file in text mode.
  • Using write() instead of pickle.dump().
  • Trying to read beyond the end of the file without handling EOFError.
  • Opening a file in wb mode accidentally, which overwrites existing records.

Exam Tips

  • Remember that binary files require the pickle module.
  • dump() writes one Python object to a binary file.
  • load() reads one object at a time from a binary file.
  • Handle EOFError while reading multiple records.
  • Practice programs for creating, searching, appending, and updating records, as these are frequently asked in CBSE practical examinations.

Frequently Asked Questions (FAQs)

1. What is a binary file?

A binary file stores data in binary format and is not human-readable.

2. Which module is used for binary file handling in Python?

The pickle module is used to store and retrieve Python objects in binary files.

3. What is the purpose of dump()?

The dump() method writes a Python object to a binary file.

4. What is the purpose of load()?

The load() method reads one Python object from a binary file.

5. Why is EOFError handled while reading binary files?

When there are no more records to read, pickle.load() raises an EOFError. Handling this exception allows the program to stop reading gracefully.


Summary

  • Binary files store data in binary format and are commonly used to store Python objects.
  • The pickle module provides dump() and load() methods for writing and reading objects.
  • Binary files use modes such as rb, rb+, wb, wb+, ab, and ab+.
  • Use pickle.dump() to create or append records.
  • Use pickle.load() to read records sequentially.
  • Searching involves reading records one by one and comparing values.
  • Updating requires reading all records, modifying the desired record, and rewriting the file.
  • Always handle EOFError when reading multiple records from a binary file.