Handling Binary Files

Carson West

File Handling

Handling Binary Files

This note covers reading and writing binary data in Python. Crucially, it differs from text file handling because we’re dealing with raw bytes rather than human-readable characters.

Key functions:

Example:

#Writing to a binary file
with open("myfile.bin", "wb") as f:
    data = b"\x00\x01\x02\x03" #Example bytes literal
    f.write(data)

#Reading from a binary file
with open("myfile.bin", "rb") as f:
    data = f.read()
    print(data) #Output: b'\x00\x01\x02\x03'

#Reading into a buffer
with open("myfile.bin", "rb") as f:
    buffer = bytearray(4) #Pre-allocate a buffer of 4 bytes.
    bytes_read = f.readinto(buffer)
    print(buffer) #Output: bytearray(b'\x00\x01\x02\x03')
    print(bytes_read) #Output: 4

Important Considerations:

File I/O Basics
Exception Handling