Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📁 Unit 1 – File Handling  ·  Lesson 07

Binary Files with pickle

What is a binary file?

A binary file stores data as raw bytes in the same form the computer uses in memory, not as readable characters. Opening it in Notepad shows strange symbols. Binary files are compact and can store whole Python objects — lists, dictionaries, tuples — exactly as they are.

Pickling and unpickling

['Asha', 91.5]Python objectpickle.dump()pickling (serialise)0x80 0x04 …bytes in student.datpickle.load()unpickling['Asha', 91.5]same object back
The pickle module converts objects ↔ bytes

pickle.dump() and pickle.load()

Syntax
import pickle
pickle.dump(object, file_object)     # file opened in 'wb' or 'ab'
object = pickle.load(file_object)    # file opened in 'rb'
Python
import pickle
data = {'roll': 1, 'name': 'Asha', 'marks': 91.5}
with open('one.dat', 'wb') as f:          # 'wb' = write binary
    pickle.dump(data, f)                  # serialise (pickle) the object
with open('one.dat', 'rb') as f:          # 'rb' = read binary
    back = pickle.load(f)                 # deserialise (unpickle)
print(back, type(back))
{'roll': 1, 'name': 'Asha', 'marks': 91.5} <class 'dict'>

Writing many records

Python
import pickle
def write_records():
    students = [[1, 'Asha', 91.5], [2, 'Ravi', 72.0], [3, 'Neha', 85.0], [4, 'Kabir', 64.5]]
    with open('student.dat', 'wb') as f:
        for rec in students:
            pickle.dump(rec, f)           # one dump per record
    print(len(students), 'records written')
write_records()
4 records written

Reading till EOFError

Python
import pickle
def read_all():
    with open('student.dat', 'rb') as f:
        while True:
            try:
                rec = pickle.load(f)
                print(rec)
            except EOFError:              # end of file reached
                break
read_all()
[1, 'Asha', 91.5] [2, 'Ravi', 72.0] [3, 'Neha', 85.0] [4, 'Kabir', 64.5]

The while True … except EOFError: break pattern is the standard board answer for reading every record.

Python
import pickle
def search(roll):
    found = False
    with open('student.dat', 'rb') as f:
        try:
            while True:
                rec = pickle.load(f)
                if rec[0] == roll:
                    print('Found:', rec)
                    found = True
        except EOFError:
            pass
    if not found:
        print('Roll', roll, 'not found')
search(3)
search(9)
Found: [3, 'Neha', 85.0] Roll 9 not found
Python
import pickle
def count_above(limit):
    n = 0
    with open('student.dat', 'rb') as f:
        try:
            while True:
                if pickle.load(f)[2] > limit:
                    n += 1
        except EOFError:
            pass
    return n
print('Students above 80:', count_above(80))
Students above 80: 2

Appending records

Python
import pickle
def append_record(rec):
    with open('student.dat', 'ab') as f:   # 'ab' keeps old records
        pickle.dump(rec, f)
append_record([5, 'Meher', 88.0])
with open('student.dat', 'rb') as f:
    recs = []
    try:
        while True:
            recs.append(pickle.load(f))
    except EOFError:
        pass
print(len(recs), 'records; last =', recs[-1])
5 records; last = [5, 'Meher', 88.0]

Updating a record

  1. 1Open in rb and load all records into a list.
  2. 2Find the record and change it in the list.
  3. 3Open in wb and dump every record again.
Read – modify – write back
Python
import pickle
def update_marks(roll, new_marks):
    recs = []
    with open('student.dat', 'rb') as f:          # 1. read all records
        try:
            while True:
                recs.append(pickle.load(f))
        except EOFError:
            pass
    for r in recs:                                # 2. change in memory
        if r[0] == roll:
            r[2] = new_marks
    with open('student.dat', 'wb') as f:          # 3. write all back
        for r in recs:
            pickle.dump(r, f)
update_marks(2, 78.0)
with open('student.dat', 'rb') as f:
    pickle.load(f)
    print(pickle.load(f))                         # second record
[2, 'Ravi', 78.0]

Deleting a record

Python
import pickle
def delete_record(roll):
    keep = []
    with open('student.dat', 'rb') as f:
        try:
            while True:
                r = pickle.load(f)
                if r[0] != roll:
                    keep.append(r)
        except EOFError:
            pass
    with open('student.dat', 'wb') as f:
        for r in keep:
            pickle.dump(r, f)
    print('Remaining rolls:', [r[0] for r in keep])
delete_record(4)
Remaining rolls: [1, 2, 3, 5]

Dumping a whole collection

Python
import pickle
# A whole list or dictionary can also be dumped in ONE go
book = {'B1': ('Python', 450), 'B2': ('SQL', 380)}
with open('books.dat', 'wb') as f:
    pickle.dump(book, f)
with open('books.dat', 'rb') as f:
    b = pickle.load(f)
for code, (title, price) in b.items():
    print(code, title, price)
B1 Python 450 B2 SQL 380

tell() and seek() in binary files

Python
import pickle
with open('student.dat', 'rb') as f:
    pickle.load(f)
    pos = f.tell()                # byte position after the first record
    second = pickle.load(f)
    f.seek(pos)                   # go back and read the same record again
    print(second == pickle.load(f), pos > 0)
True True

Text vs binary files

Text file

  • Stores characters; readable in Notepad
  • Each line ends with \n (EOL)
  • Modes r, w, a
  • Slower for big structured data

Binary file

  • Stores bytes; not human-readable
  • No line structure
  • Modes rb, wb, ab, rb+
  • Fast; stores Python objects with pickle
Text vs binary

Summary & practice

  • Binary files hold bytes; open with rb / wb / ab.
  • pickle.dump(obj, f) writes; pickle.load(f) reads one object; EOFError marks the end.
  • Search/count with a load loop; update/delete by reading all, changing, rewriting.
✅ Board-style question

A binary file EMP.DAT has records [EmpID, Name, Salary]. Write def CountHigh(): to display and count employees whose salary is more than 50000.

Frequently Asked Questions

What is pickling?
Converting a Python object (list, dictionary, tuple…) into a stream of bytes so it can be stored in a binary file. Unpickling converts the bytes back into the same object.
Why do we catch EOFError while reading a binary file?
We usually do not know how many records the file has. pickle.load() raises EOFError when there is nothing left to read, so catching it is the signal to stop the loop.
How is a record updated in a binary file?
Read all records into a list, change the required record in memory, then write the whole list back with mode "wb". (Advanced: use tell() and seek() to overwrite in place when sizes are equal.)
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicCSV Files: reader & writer Your progress: 7 / 26 (27%) · Lesson 8 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free