Sub topic 15
Encodings and newline handling
This chapter assumes you can open files with open() and a with block, and that you know the difference between str and bytes at a basic level. It covers two details that cause most "works on my machine" file bugs: which encoding turns text into bytes, and how line endings are translated.
Text and bytes
A file stores bytes. A Python str holds characters. An encoding is the rule that converts between them. UTF-8 is the encoding to use unless a file format says otherwise.
text = "café"
data = text.encode("utf-8")
print(data)
print(len(text), len(data))
print(data.decode("utf-8"))
print(data.decode("latin-1"))The output is b'caf\xc3\xa9', then 4 5, then café, then café. The character é takes two bytes in UTF-8, so the byte count is larger than the character count. Decoding with the wrong encoding does not fail here. It produces garbled text called mojibake.
Always name the encoding
If you call open() without encoding, Python uses the platform's default. That default differs between systems, so a file written on one machine may not read correctly on another. Pass encoding="utf-8" every time you open a text file.
Handling undecodable bytes
When bytes are not valid in the chosen encoding, decode() raises UnicodeDecodeError. The errors argument changes that behavior.
raw = b"caf\xe9"
print(raw.decode("utf-8", errors="replace"))
print(raw.decode("latin-1"))The first call prints caf�, with a replacement character in place of the bad byte. The second prints café, because byte \xe9 is é in Latin-1. Use errors="replace" only when losing a character is acceptable. Otherwise find the file's real encoding.
Newline handling
Windows ends lines with \r\n. Linux and macOS use \n. Python hides this difference through the newline argument of open().
| Mode | `newline` value | Behavior |
|---|---|---|
| Read | `None` (default) | `\n`, `\r`, and `\r\n` all become `\n` |
| Read | `""` | Lines split on any ending, but the ending is kept unchanged |
| Write | `None` (default) | `\n` becomes the platform's line separator |
| Write | `""` or `"\n"` | No translation |
| Write | `"\r\n"` | `\n` becomes `\r\n` |
The code below writes Windows line endings and reads them back three ways.
with open("lines.txt", "w", encoding="utf-8", newline="\r\n") as f:
f.write("one\ntwo\n")
with open("lines.txt", "rb") as f:
print(f.read())
with open("lines.txt", encoding="utf-8") as f:
print(repr(f.read()))
with open("lines.txt", encoding="utf-8", newline="") as f:
print(repr(f.read()))The three outputs are:
b'one\r\ntwo\r\n', the raw bytes on disk.'one\ntwo\n', because the default read translates endings.'one\r\ntwo\r\n', becausenewline=""leaves them alone.
Use newline="" when you must preserve the original endings, and when working with the csv module, which handles line endings itself. The rb mode skips decoding and newline translation entirely.
Common mistakes
- Reading a file with a different encoding than it was written with.
- Assuming
len(text)equals the file size in bytes. - Opening a CSV file without
newline="", which can add blank rows on Windows. - Using
errors="ignore", which silently drops data and hides the real problem.
Exercise
You write the string "naïve\n" to a file with open("a.txt", "w", encoding="utf-8"), then read it back with open("a.txt", encoding="ascii"). What happens, and how do you fix it?
Show answer
The read raises UnicodeDecodeError, because "ï" is encoded as two bytes that are not valid ASCII. Fix it by reading with encoding="utf-8", the same encoding used for writing.
Exercise
A file was saved on Windows with \r\n line endings. You must copy it to a new file with the endings unchanged, using text mode. Which newline argument do you use when reading?
Show answer
Use newline="" when reading, so \r\n is not translated to \n. Use newline="" when writing as well, so no further translation happens.