=open("binfile.bin","wb")
f=[5, 10, 15, 20, 25]
num=bytearray(num)
arr
f.write(arr) f.close()
Handling Binary Files
If we don’t want to deal only with text files, Python has a way to read and write any file as a binary sequence.
You can check how any file is composed of binary numbers by opening in a hexadecimal viewer/editor such as in https://hexed.it/
Writing to a binary file
- You will have to use the types
byte
andbytearray
to deal with binary data. For example, the following code creates a binary file with some integers specified in thenum
list. - Notice that a file is opened as binary by adding the
b
character to the second argument inopen
:
Some exploration activities: - Check how the type bytearray
works (exploring the variable arr
) - Open the file “binfile.bin” in a hexadecimal editor and try to see the binary numbers there
Reading from a binary file
- You can read a binary file by adding the
b
character to the second argument inopen
:
=open("binfile.bin","rb") f
Example: reading data from a bmp file
- A bitmap file is a standard format containing a 54 byte header specifying the size of the image and other parameters.
- You can read the following code and try to figure out what the function
read_bmp_pixels
is doing.- Notice the function
seek()
that is used to position a kind of “cursor” at some point of the binary file
- Notice the function
def read_bmp_pixels(file_path):
with open(file_path, 'rb') as f:
# Read header
= f.read(54) # BMP header is 54 bytes
header
# Extract width and height from the header
= int.from_bytes(header[18:22], byteorder='little')
width = int.from_bytes(header[22:26], byteorder='little')
height
# Calculate the size of pixel data
= width * height * 3 # For 24-bit BMP (3 bytes per pixel)
pixel_data_size
# Move file pointer to the beginning of pixel data
54)
f.seek(
# Read pixel data
= f.read(pixel_data_size)
pixel_data
return pixel_data, width, height
# Example usage
= 'example.bmp'
file_path = read_bmp_pixels(file_path)
pixels, width, height print(f"Width: {width}, Height: {height}")
print(f"Total Pixels: {width * height}")
print(f"Pixel data size: {len(pixels)} bytes")
- Later, try to open a bmp file from your computer and recognize the color pixels in this binary data. Every pixel is represented by three bytes, referring to the red, green and blue (RGB) components of the pixel.