PythonFile HandlingWorking with Binary Files

Working with Binary Files in Python

Binary files store data in a format that is not human-readable but is efficient for storage and processing. Python allows you to handle binary data using file operations in binary mode.


Opening a File in Binary Mode

To work with binary files, open the file in binary mode using the b flag:

  • 'rb': Read binary data.
  • 'wb': Write binary data.
  • 'ab': Append binary data.

Example: Opening a Binary File

# Opening a file in binary read mode
with open("example.bin", "rb") as binary_file:
    data = binary_file.read()
    print("Binary data:", data)

Writing Binary Data

Binary data can be written to a file using the wb mode.

Example: Writing Binary Data

binary_data = b"This is binary data."
 
with open("example.bin", "wb") as binary_file:
    binary_file.write(binary_data)

Reading Binary Data

When reading binary files, the data is returned as a bytes object, which can be processed as needed.

Example: Reading Binary Data

with open("example.bin", "rb") as binary_file:
    data = binary_file.read()
    print("Read binary data:", data)

Example: Reading and Writing Images

Binary files are commonly used to handle non-text data, such as images.

Example: Copying an Image

# Read an image file in binary mode
with open("input_image.jpg", "rb") as input_file:
    image_data = input_file.read()
 
# Write the image data to a new file
with open("output_image.jpg", "wb") as output_file:
    output_file.write(image_data)

Example: Handling Serialized Objects

Serialized objects (e.g., pickle-dumped data) are stored as binary files. Python’s pickle module can be used to work with such files.

Example: Writing Serialized Data

import pickle
 
data = {"name": "Alice", "age": 25, "is_student": True}
 
# Serialize and save data
with open("data.pkl", "wb") as binary_file:
    pickle.dump(data, binary_file)

Example: Reading Serialized Data

import pickle
 
# Read and deserialize data
with open("data.pkl", "rb") as binary_file:
    data = pickle.load(binary_file)
    print("Deserialized data:", data)

Key Points to Remember

  1. Binary vs. Text Files: Binary files store data as bytes, while text files store data as human-readable text.
  2. Data Integrity: Be cautious when reading and writing binary files to avoid corruption.
  3. Use Context Managers: Always use with statements to manage file resources efficiently.

Practice Problems

Problem 1: Copy a Binary File

Write a program to read a binary file and create an exact copy of it.

Show Solution
with open("source.bin", "rb") as source_file:
    data = source_file.read()
 
with open("copy.bin", "wb") as copy_file:
    copy_file.write(data)

Problem 2: Serialize and Deserialize Data

Write a program to serialize a dictionary, save it to a binary file, and then read it back.

Show Solution
import pickle
 
# Serialize and save
data = {"key": "value", "number": 42}
with open("data.pkl", "wb") as binary_file:
    pickle.dump(data, binary_file)
 
# Deserialize and load
with open("data.pkl", "rb") as binary_file:
    loaded_data = pickle.load(binary_file)
    print("Loaded data:", loaded_data)

Working with binary files in Python enables efficient handling of non-text data such as images, videos, and serialized objects. Experiment with these examples to gain a deeper understanding!


Pyground

Play with Python!

Output: