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
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.
Last updated