85. Working with Binary Files
Working with binary files in Python can be done efficiently using the built-in file handling functions. Python allows reading and writing binary data with the rb (read binary) and wb (write binary) modes, and offers other utilities like struct for unpacking and packing binary data.
Here are 10 Python code snippets demonstrating how to work with binary files:
1. Reading Binary Data from a File
# Read binary data from a file
with open('example.bin', 'rb') as file:
binary_data = file.read()
# Display the first 10 bytes
print(binary_data[:10])This code reads the entire content of a binary file and prints the first 10 bytes.
2. Writing Binary Data to a File
# Write binary data to a file
data = b'\x00\x01\x02\x03\x04\x05\x06\x07'
with open('output.bin', 'wb') as file:
file.write(data)This snippet writes a sequence of bytes to a binary file.
3. Reading a Specific Number of Bytes from a Binary File
# Read the first 10 bytes from a binary file
with open('example.bin', 'rb') as file:
chunk = file.read(10)
print(chunk)Here, we use file.read(10) to read the first 10 bytes from the binary file.
4. Reading Binary Data in Chunks
This code reads a binary file in chunks, yielding each chunk without loading the entire file into memory.
5. Writing Binary Data with a Loop
This example demonstrates writing binary data in smaller chunks (5 bytes at a time).
6. Using struct to Pack and Unpack Binary Data
This code demonstrates packing and unpacking binary data using the struct module. It writes an integer and a string to a binary file and then reads and unpacks the data.
7. Reading and Writing a Binary File in 'rb' and 'wb' Modes
This snippet copies the content of one binary file to another by reading in binary mode (rb) and writing in binary mode (wb).
8. Modifying Specific Bytes in a Binary File
This example opens a file in read and write mode (r+b) and modifies a specific byte at a given position in the file.
9. Binary File with Metadata (e.g., Header + Data)
This snippet writes a binary file that includes a header and binary data.
10. Reading Binary File and Converting to a Hexadecimal String
This code reads binary data from a file and converts it to a hexadecimal string using the hex() method for better readability.
These examples cover basic operations such as reading and writing binary files, using the struct module for packing and unpacking binary data, and modifying specific bytes in a binary file. They also show how to handle binary data efficiently when working with large files.
Last updated