Binary mode makes Python file operations work with bytes rather than strings. Add `b` to the mode passed to `open`: use `'rb'` to read bytes or `'wb'` to write them. Choose it when data is not text, when a byte sequence must be preserved, or when a stream must be interpreted as bytes even though it resembles text. section 13.4.1 section 21.2.1
Reading with `open("myfile", "rb")`:
- `read(4)` returns up to four bytes from the current position—useful for a fixed-size header. section 13.4.1
- `read()` returns the remaining file data as one `bytes` object. section 13.4.1
- To use the result as a string, decode the bytes first. section 13.4.1
input_file = open("myfile", 'rb') #1
header = input_file.read(4) #2
data = input_file.read() #3
input_file.close()
The first read takes a four-byte header; the next takes the rest of the file. section 13.4.1
Unlike text mode, binary reads return the file’s bytes without newline translation. Text mode can normalize line endings, and text writes can map `\n` to platform-specific endings. Unicode also makes byte counts different from character counts, so decide which quantity a counting utility needs. section 13.4 section 13.10.1
open('test.txt', 'wb').write(bytes([65, 66, 67, 255, 192,193]))
Writing explicit byte values creates a file that includes bytes an ordinary UTF-8 text read cannot decode; that read raises `UnicodeDecodeError`. section 21.2.1
