Class 12 Computer Science Python Binary Files


In Python, a binary file is a file that contains data in a format that is not human-readable—it’s stored as a sequence of bytes rather than plain text. These files can include images, audio, video, compiled programs, or any other data that isn’t meant to be interpreted as text.

🔍 Key Characteristics of Binary Files

  • Raw byte format: Data is stored as raw bytes, not characters.
  • Efficient storage: Ideal for storing complex data structures or large files.
  • Requires binary mode: Must be opened using 'rb' (read binary) or 'wb' (write binary) modes.

📘 How to Work with Binary Files in Python

Opening a Binary File

with open('example.bin', 'rb') as file:
    data = file.read()

Writing to a Binary File

with open('example.bin', 'wb') as file:
    file.write(b'\xDE\xAD\xBE\xEF')  # Writing bytes

🧠 Use Cases

  • Reading/writing images (.jpg, .png)
  • Handling audio/video files (.mp3, .mp4)
  • Storing serialized Python objects using pickle
  • Communicating with hardware or low-level systems

pickle Module 

The pickle module in Python is a powerful tool for serializing and deserializing Python objects, allowing them to be saved to a binary file and later restored. Serialization, or “pickling,” converts a Python object into a byte stream, which can be stored in a file or transmitted over a network. Deserialization, or “unpickling,” reconstructs the original object from the byte stream. This module is especially useful for saving complex data structures like dictionaries, lists, or custom classes. To use it, you typically open a file in binary mode and call pickle.dump() to write the object, and pickle.load() to read it back. It’s important to note that pickle is Python-specific and not secure against malicious data—so it’s best used with trusted sources. 

🥒Pickling

Definition: Pickling is the process of converting a Python object into a byte stream so it can be saved to a binary file or transmitted over a network.

Example:

python
import pickle

data = {'name': 'Amit', 'age': 25, 'is_student': True}

# Pickling the data
with open('data.pkl', 'wb') as file:
    pickle.dump(data, file)

This saves the dictionary data into a binary file named data.pkl.

 

🔓 Unpickling

Definition: Unpickling is the process of converting the byte stream back into the original Python object.

Example:

python
import pickle

# Unpickling the data
with open('data.pkl', 'rb') as file:
    loaded_data = pickle.load(file)

print(loaded_data)

This reads the binary file and reconstructs the original dictionary: {'name': 'Amit', 'age': 25, 'is_student': True}.

 

⚠️ Important Notes

  • Pickled files are not human-readable.

  • Only use pickle with trusted data sources—it can execute arbitrary code during unpickling.

🥒 pickle.dump( ) — Function Overview

🔧 Syntax

python
pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

📌 Parameters Explained

Parameter Description
obj The Python object you want to serialize (e.g., list, tuple, class instance).
file A writable binary file object (opened with 'wb' mode).
protocol Optional. Specifies the pickling protocol version (0 to 5). Default is highest available.
fix_imports Optional. Used for compatibility between Python 2 and 3. Default is True.
buffer_callback Optional. Used for out-of-band data handling in advanced scenarios.
 
 

✅ Examples of pickle.dump( )

1. Pickling a List

python
import pickle

colors = ['red', 'green', 'blue']

with open('colors.pkl', 'wb') as f:
    pickle.dump(colors, f)

2. Pickling a Tuple with Protocol 0

python
numbers = (1, 2, 3)

with open('numbers.pkl', 'wb') as f:
    pickle.dump(numbers, f, protocol=0)

3. Pickling a Custom Object

python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

s1 = Student('Amit', 'A')

with open('student.pkl', 'wb') as f:
    pickle.dump(s1, f)
 

🧠 Notes

  • Always open the file in binary mode ('wb') when using dump().

  • The protocol parameter helps control compatibility and efficiency.

  • Pickled files are not human-readable and should only be used with trusted sources.

Pickle.load( ) function

The pickle.load() function in Python is used to deserialize or unpickle a Python object from a binary file. It reads the byte stream created by pickle.dump() and reconstructs the original Python object.

 

🔓 Pickle.load( )  — Function Overview

🔧 Syntax

python
pickle.load(file)
  • file: A readable binary file object (opened with 'rb' mode).

  • Returns the original Python object that was pickled.

 

✅ Examples with try Block

Using try ensures your code handles errors gracefully, like missing files or corrupted data.

 

1. Unpickling a List of Integers

python
import pickle

try:
    with open('integers.pkl', 'rb') as f:
        numbers = pickle.load(f)
    print("Loaded numbers:", numbers)
except FileNotFoundError:
    print("File not found.")
except pickle.UnpicklingError:
    print("Unpickling failed.")
except Exception as e:
    print("Unexpected error:", e)
 

2. Unpickling a Tuple of Strings

python
try:
    with open('names.pkl', 'rb') as f:
        names = pickle.load(f)
    print("Names:", names)
except FileNotFoundError:
    print("File not found.")
except pickle.UnpicklingError:
    print("Unpickling failed.")
except Exception as e:
    print("Unexpected error:", e)
 

3. Unpickling a Custom Object

python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

try:
    with open('student.pkl', 'rb') as f:
        student = pickle.load(f)
    print("Student:", student.name, student.grade)
except FileNotFoundError:
    print("File not found.")
except pickle.UnpicklingError:
    print("Unpickling failed.")
except Exception as e:
    print("Unexpected error:", e)
 

These examples show how pickle.load() can recover various Python objects safely.

error: Content is protected !!