All files store bytes (numbers from 0 to 255). A text file is the case in which those bytes represent letters according to an encoding. A binary file is any other: images, music, programs, compressed documents… They cannot be read as text, but they can be handled byte by byte.
The bytes type
When you open a file in binary mode, Python does not give you strings (str) but bytes objects: sequences of numbers from 0 to 255.
data = b"Hello" # a bytes literal: a b before the quotes
print(data) # b'Hello'
print(len(data)) # 5
print(data[0]) # 72 ← a number, not a letter
print(list(data)) # [72, 101, 108, 108, 111]
print(data[1:3]) # b'el' ← a slice gives another bytes
Notice the key difference: indexing a str gives another str, indexing a bytes gives an integer.
From text to bytes and back
text = "Año"
raw = text.encode("utf-8")
print(raw) # b'A\xc3\xb1o' (the ñ takes 2 bytes)
print(len(text), len(raw)) # 3 4
print(raw.decode("utf-8")) # Año
str.encode(encoding)converts text into bytes.bytes.decode(encoding)converts bytes into text. If the bytes are not valid in that encoding, it raisesUnicodeDecodeError."latin-1"is a one-byte-per-character encoding that never fails when decoding: it serves for data whose text is ASCII/Latin-1.
Binary open modes
| Mode | What it does |
|---|---|
"rb" | Read bytes |
"wb" | Write bytes (deletes what was there) |
"ab" | Append bytes at the end |
"r+b" | Read and write over a file that already exists, without deleting it |
In binary mode encoding is not used: Python interprets nothing, it gives you the bytes as they are.
with open("data.bin", "wb") as f:
f.write(b"ABC")
f.write(bytes([0, 255, 10])) # bytes from numbers
with open("data.bin", "rb") as f:
content = f.read()
print(content) # b'ABC\x00\xff\n'
print(len(content)) # 6
Remember: write in binary mode only accepts bytes, not str. f.write("ABC") raises TypeError.
Bytes and hexadecimal
Programmers show bytes in hexadecimal (base 16), because each byte is exactly two digits, from 00 to ff:
print(b"Hello".hex()) # 48656c6c6f
print(f"{72:02x}") # 48
print(bytes.fromhex("48656c6c6f")) # b'Hello'