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
Copy
# 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
Copy
# 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
Copy
Here, we use file.read(10) to read the first 10 bytes from the binary file.
4. Reading Binary Data in Chunks
Copy
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
Copy
This example demonstrates writing binary data in smaller chunks (5 bytes at a time).
6. Using struct to Pack and Unpack Binary Data
Copy
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
Copy
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
Copy
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)
Copy
This snippet writes a binary file that includes a header and binary data.
10. Reading Binary File and Converting to a Hexadecimal String
Copy
This code reads binary data from a file and converts it to a hexadecimal string using the hex() method for better readability.
# Read the first 10 bytes from a binary file
with open('example.bin', 'rb') as file:
chunk = file.read(10)
print(chunk)
# Read binary data in chunks
def read_in_chunks(file_path, chunk_size=64):
with open(file_path, 'rb') as file:
while chunk := file.read(chunk_size):
yield chunk
# Example usage
for chunk in read_in_chunks('large_binary_file.bin'):
print(chunk)
# Write binary data in chunks
data = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
with open('output.bin', 'wb') as file:
for i in range(0, len(data), 5):
file.write(data[i:i+5]) # Writing 5 bytes at a time
import struct
# Packing data
data = struct.pack('I 5s', 12345, b'hello')
with open('packed.bin', 'wb') as file:
file.write(data)
# Unpacking data
with open('packed.bin', 'rb') as file:
data = file.read()
unpacked_data = struct.unpack('I 5s', data)
print(unpacked_data)
# Read a binary file and write to another binary file
with open('source_file.bin', 'rb') as read_file:
data = read_file.read()
with open('destination_file.bin', 'wb') as write_file:
write_file.write(data)
# Modify specific bytes in a binary file
with open('example.bin', 'r+b') as file:
file.seek(4) # Move to the 4th byte
file.write(b'\xFF') # Replace the byte at that position
# Create a binary file with a header and data
header = b'HEADER'
data = b'Hello, this is binary data.'
with open('header_data.bin', 'wb') as file:
file.write(header) # Write header
file.write(data) # Write data
# Read a binary file and convert to hexadecimal representation
with open('example.bin', 'rb') as file:
binary_data = file.read()
hex_representation = binary_data.hex()
print(hex_representation)