Binary data represents information as encoded bytes rather than directly as human-readable text characters. Python handles it with bytes objects and binary file modes such as rb and wb. section 13.0 section 6.9
Use binary data when:
- A file is generated or consumed by another program and follows a defined binary format. section 13.7
- A Path object should read or write bytes directly through read_bytes and write_bytes. section 13.5
- A string must cross the text boundary: encode converts it to bytes, while decode converts bytes back to a string. section 6.9
Bytes may look like strings, but they are a different type and cannot be combined directly with strings. For structured records, struct format strings describe fields, pack writes them as bytes, and unpack restores values. section 13.7 section 6.9
Writing and reading a structured record
The format 'hd7s' describes a short integer, a double-precision float, and seven characters. struct.pack('hd7s', 42, 3.14, b'goodbye') creates one record. Reading record-sized chunks and applying struct.unpack produces [(42, 3.14, b'goodbye')].
from pathlib import Path
p_text = Path('my_text_file')
p_text.write_text('Text file contents')
18 #1
p_text.read_text()
'Text file contents'
p_binary = Path('my_binary_file')
p_binary.write_bytes(b'Binary file contents')
20 #1
p_binary.read_bytes()
b'Binary file contents' #2
#1 Number of bytes written
#2 Data as bytes
Compare text and binary Path operations: write_text/read_text use strings, while write_bytes/read_bytes use bytes and replace existing content rather than append. section 13.5



