๐ฆ 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?
Term | Meaning |
---|---|
Pickling | Converting a Python object into a byte stream (saving to file) |
Unpickling | Converting a byte stream back to a Python object (loading from file) |
๐ง Importing the Module
๐ Writing to a Binary File (Pickling)
✔️ pickle.dump(object, file)
is used to save the object.
๐ Reading from a Binary File (Unpickling)
✔️ pickle.load(file)
reads and restores the object.
๐ Storing Multiple Records
๐ Reading Multiple Records
๐ Why try-except
? Because pickle.load()
raises EOFError when it reaches the end of the file.
๐ Updating a Record in a Binary File
- Read all records.
- Modify the target.
- Rewrite all back.
⚠️ 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
๐น Program 2: Display all student names who scored above 80
❓ Practice Questions:
๐ 1 Mark – Objective:
-
What is the purpose of
pickle.dump()
? - Which error is raised when end of file is reached?
- Which file mode is used to read binary files?
✍️ 2 Marks – Short Answer:
-
Differentiate between
dump()
andload()
functions. - Why can’t we use
read()
to read binary files?
๐ป 3 Marks – Programming:
-
Write a program to store 3 student records using
pickle
. - 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.