What distinguishes binary files from text files when handling them in Python?
Binary files (like images, audio, or executables) contain data as raw bytes, not human-readable characters.
Key Difference: Python does not automatically decode or encode characters when reading/writing binary files. You work directly with bytes objects rather than str objects. You must explicitly use binary modes (‘rb’, ‘wb’, etc.) when opening them.
How do you open a file in binary mode for reading and writing?
Add the letter ‘b’ to the standard file mode (‘r’, ‘w’, ‘a’).
Reading binary: Use the mode ‘rb’.
Writing binary: Use the mode ‘wb’.
Appending binary: Use the mode ‘ab’.
with open("image.jpg", "rb") as f:
# File operations hereWhat type of data do file reading methods return in binary mode?
When reading a file opened in binary mode, methods like .read(), .readline(), and .readlines() return bytes objects, not strings.
with open("data.bin", "rb") as f:
data = f.read(5)
print(type(data)) # Output: <class 'bytes'>
print(data) # Output: b'\x01\x02\x03\x04\x05'How do you write data to a binary file?
You must provide a bytes object (or a byte array) to the .write() method when the file is opened in binary write mode (‘wb’ or ‘ab’).
data_to_write = b'\x48\x65\x6C\x6C\x6F' # Bytes representing "Hello"
with open("output.bin", "wb") as f:
f.write(data_to_write)Can you use seek() and tell() in binary mode?
Yes, seek() and tell() work well in binary mode. In fact, binary mode is often preferred for precise positioning because the “offset” always refers to a specific byte count, unlike text mode where character encoding can make positioning ambiguous.
with open("file.bin", "rb") as f:
f.seek(100) # Move exactly 100 bytes from the start
current_pos = f.tell()
print(f"Current byte position: {current_pos}")