12.5 ๐Ÿ’พ Binary File Handling in Python – Class XII CBSE Made Easy

 

๐Ÿ“ฆ What is a Binary File?

A binary file stores data in a format not readable by humans — it’s meant to be interpreted by programs. This is ideal for storing:

  • Numbers
  • Lists, dictionaries
  • User-defined objects

In Python, we use the pickle module to serialize (write) and deserialize (read) objects to/from binary files.


๐Ÿ› ️ What is Pickling and Unpickling?

TermMeaning
PicklingConverting a Python object into a byte stream (saving to file)
UnpicklingConverting a byte stream back to a Python object (loading from file)

๐Ÿ”ง Importing the Module


import pickle

๐Ÿ“ Writing to a Binary File (Pickling)


import pickle data = [101, "Rahul", 91.2] f = open("student.dat", "wb") # 'wb' = write binary pickle.dump(data, f) f.close()

✔️ pickle.dump(object, file) is used to save the object.


๐Ÿ“– Reading from a Binary File (Unpickling)


import pickle f = open("student.dat", "rb") # 'rb' = read binary data = pickle.load(f) print(data) f.close()

✔️ pickle.load(file) reads and restores the object.


๐Ÿ”„ Storing Multiple Records


import pickle f = open("records.dat", "wb") for i in range(3): name = input("Enter name: ") marks = float(input("Enter marks: ")) rec = [name, marks] pickle.dump(rec, f) f.close()

๐Ÿ“‚ Reading Multiple Records


import pickle f = open("records.dat", "rb") try: while True: rec = pickle.load(f) print(rec) except EOFError: f.close()

๐Ÿ›‘ Why try-except? Because pickle.load() raises EOFError when it reaches the end of the file.


๐Ÿ” Updating a Record in a Binary File

  1. Read all records.
  2. Modify the target.
  3. Rewrite all back.


import pickle f1 = open("records.dat", "rb") f2 = open("temp.dat", "wb") try: while True: rec = pickle.load(f1) if rec[0] == "Rahul": rec[1] = 95.0 # updating marks pickle.dump(rec, f2) except EOFError: f1.close() f2.close() import os os.remove("records.dat") os.rename("temp.dat", "records.dat")

⚠️ Important Points:

  • Binary files cannot be opened in text editors.
  • Always use 'rb' and 'wb' for binary mode.
  • Use try-except to handle end-of-file errors.
  • Don’t forget to import pickle before use.


๐Ÿ’ก Example Programs

๐Ÿ”น Program 1: Write a list of student records to a binary file


students = [["Ravi", 85], ["Anu", 92], ["Mohit", 78]] with open("stud.dat", "wb") as f: for s in students: pickle.dump(s, f)

๐Ÿ”น Program 2: Display all student names who scored above 80


with open("stud.dat", "rb") as f: try: while True: rec = pickle.load(f) if rec[1] > 80: print(rec[0]) except EOFError: pass

❓ Practice Questions:

๐Ÿ“˜ 1 Mark – Objective:

  1. What is the purpose of pickle.dump()?
  2. Which error is raised when end of file is reached?
  3. Which file mode is used to read binary files?

✍️ 2 Marks – Short Answer:

  1. Differentiate between dump() and load() functions.
  2. Why can’t we use read() to read binary files?

๐Ÿ’ป 3 Marks – Programming:

  1. Write a program to store 3 student records using pickle.
  2. Write a program to read all records and display those with names starting with 'A'.

๐Ÿง  5 Marks – Case-Based:

A file named employee.dat contains multiple employee records in the format: [ID, Name, Salary]. Write a program to:

  • Read the file
  • Increase salary by 10% for all employees earning below ₹20,000
  • Save updated records back to file


๐ŸŽฏ Tips to Remember:

  • Always use binary mode ('wb', 'rb') for binary files.
  • Use EOFError to stop reading in a loop.
  • Pickling works best with lists, dicts, and even user-defined classes.

✅ Conclusion

Binary file handling is useful for efficient data storage, especially when you need to store complex data structures. With just a few functions from the pickle module, you can master this high-scoring topic for your CBSE Class XII board exam.

Previous Post Next Post