How do you handle binary files in python? Flashcards

(5 cards)

1
Q

What distinguishes binary files from text files when handling them in Python?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you open a file in binary mode for reading and writing?

A

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 here
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What type of data do file reading methods return in binary mode?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you write data to a binary file?

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can you use seek() and tell() in binary mode?

A

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}")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly