Text mode changes bytes on its way in and out. Binary mode changes nothing, which is the difference when the file is not text.
What you will see
8
About 2 min of reading
Quick check
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Try It
Check byte behaviour.
1
Bytes and first value.
data = b"ab"
print(len(data), data[0])
Before you run it, say out loud what it will print. Then open the answer.
What it prints
2 97
2
Length kept.
out = "a\r\nb"
print(len(out))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
4
3
Header bytes.
data = b"\x89PNG"
print(len(data))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
4
4
Total size.
head = b"# note"
body = b"\x00\x01"
print(len(head) + len(body))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
8
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
Text mode translates bytes on the way in and out. Binary mode does not, so non-text files must use binary.
1pick a mode
↓
2keep the bytes
↓
3decode at the edge
↓
4count bytes for size
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
data = b"ab"sets nothing on screen
print(len(data), data[0])2 97
Why this worksMode decides the bytes
Text mode is a translation layer. When the file is not text, that layer is a bug, so open binary and decode where you need words.
Size is a byte count
Anything that reports a size counts bytes. A text length can be smaller, which is where the two numbers disagree.
Examples
Bytes in and out
data = b"ab"print(len(data), data[0])
Binary gives bytes, not a string. Indexing gives a number, not a one letter string.
Endings change
out = "a\r\nb"print(len(out))
Text mode can rewrite endings on write. Binary keeps exactly the bytes you gave.
A png has no encoding
data = b"\x89PNG"print(data[:4])
There is no encoding for an image. Opening it as text raises on the first bad byte.
Count the bytes
data = b"\x00\x01\x02"print(len(data))
Byte length is the file size. A text length counts symbols, which can differ.
Mixed files need a plan
head = b"# note"
body = b"\x00\x01"print(len(head) + len(body))
A header of text plus a body of bytes needs binary mode and a decode for the header.
Decode at the edge
data = "hi".encode("utf-8")
print(data.decode("utf-8"))
Decode once where text is needed. Keep bytes on the way through.
Words this lesson uses
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.