Sub topic 15
Encodings and newline handling
This chapter covers what happens between a Python string and the bytes on disk. It assumes you can already open, read, and write text files with a with block, and that you know the difference between str and bytes at a basic level.
Text versus bytes
A Python str is a sequence of Unicode code points. A file stores bytes. An encoding is the rule that maps code points to bytes and back. Opening a file in text mode makes Python apply an encoding on every write and the matching decoding on every read.
s = "café"
print(len(s)) # 4 code points
print(s.encode("utf-8")) # b'caf\xc3\xa9'
print(len(s.encode("utf-8"))) # 5 bytes
print(s.encode("latin-1")) # b'caf\xe9'
print(len(s.encode("latin-1"))) # 4 bytesThe same string produces different bytes under different encodings. Reading bytes with the wrong encoding gives wrong text or an error. The file does not record which encoding was used, so your code has to state it.
Why you pass `encoding` explicitly
If you omit encoding, open() uses a locale-dependent default. You can inspect it:
import locale
import sys
print(locale.getpreferredencoding(False))
print(sys.getdefaultencoding())
print(sys.getfilesystemencoding())These three values answer different questions:
| Call | What it reports |
|---|---|
| `locale.getpreferredencoding(False)` | The default `open()` uses for text files |
| `sys.getdefaultencoding()` | The encoding Python uses for `str.encode()` and `bytes.decode()` when none is given. It is always UTF-8 in Python 3. |
| `sys.getfilesystemencoding()` | The encoding used for file names |
On many Linux and macOS systems the locale default is UTF-8. On Windows it has traditionally been a legacy code page such as cp1252. Python 3.15 is planned to make UTF-8 the default everywhere, and python -X utf8 already turns on UTF-8 mode today. Until you control the interpreter version and flags, pass the encoding yourself.
Decoding and encoding errors
When bytes do not fit the encoding, Python raises an exception. Two are common.
UnicodeDecodeErrorhappens when reading bytes that are invalid in the chosen encoding.UnicodeEncodeErrorhappens when writing a character that the encoding cannot represent, such as"€"in ASCII.
data = "price: 5€".encode("utf-8")
try:
data.decode("ascii")
except UnicodeDecodeError as exc:
print(exc)
try:
"price: 5€".encode("ascii")
except UnicodeEncodeError as exc:
print(exc)The errors argument controls what happens instead of raising:
data = "price: 5€".encode("utf-8")
print(data.decode("ascii", errors="replace"))
print(data.decode("ascii", errors="ignore"))
print("price: 5€".encode("ascii", errors="backslashreplace"))
print("price: 5€".encode("ascii", errors="xmlcharrefreplace"))| `errors` value | Behavior |
|---|---|
| `strict` | Raise an exception. This is the default. |
| `replace` | Substitute `?` when encoding, or U+FFFD when decoding |
| `ignore` | Drop the offending data |
| `backslashreplace` | Write an escape such as `\u20ac` |
| `xmlcharrefreplace` | Write an XML reference such as `€` (encoding only) |
ignore and replace lose information without any signal. Use them for display or best-effort reading of messy logs, not for data you need to keep intact.
Mojibake: the wrong-but-silent case
Some mismatches raise nothing. Latin-1 maps every byte value to a character, so decoding UTF-8 bytes as Latin-1 never fails. It produces garbled text instead.
raw = "café".encode("utf-8")
print(raw.decode("latin-1"))This prints café. Garbled text of this kind is called mojibake. If you see à followed by another odd character in text that should be accented, suspect UTF-8 bytes decoded as a single-byte encoding. The fix is to find where the wrong decoding happens and change it, not to patch the text afterward.
The byte order mark
Some Windows programs write a byte order mark (BOM) at the start of a UTF-8 file. It is the three bytes EF BB BF. If you read such a file as plain utf-8, the BOM appears as the character \ufeff at the start of your first line, which breaks things like CSV header matching.
with open("bom.txt", "w", encoding="utf-8-sig") as f:
f.write("hello\n")
with open("bom.txt", "rb") as f:
print(f.read(3))
with open("bom.txt", encoding="utf-8") as f:
print(repr(f.readline()))
with open("bom.txt", encoding="utf-8-sig") as f:
print(repr(f.readline()))The utf-8-sig codec writes a BOM when encoding and removes one when decoding. It also reads files that have no BOM, so it is a safe choice for input from unknown sources. Do not use it for output unless a consuming program, such as some versions of Excel, requires the BOM.
Newline handling
Line endings differ by platform: Unix uses \n, classic Windows uses \r\n, and very old Mac systems used \r. In text mode Python hides this through the newline argument of open().
On input with newline=None (the default), \n, \r, and \r\n are all translated to \n. On output with the default, each \n you write is translated to os.linesep, which is \r\n on Windows and \n elsewhere.
You can see the effect by writing with explicit settings and inspecting the raw bytes:
with open("unix.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("a\nb\n")
with open("windows.txt", "w", encoding="utf-8", newline="\r\n") as f:
f.write("a\nb\n")
for name in ("unix.txt", "windows.txt"):
with open(name, "rb") as f:
print(name, f.read())The output is b'a\nb\n' for the first file and b'a\r\nb\r\n' for the second. The newline values behave as follows:
| Mode | `newline=` value | Effect |
|---|---|---|
| Read | `None` (default) | Universal newlines: all endings become `\n` |
| Read | `""` | Universal newlines recognized, but endings are returned untranslated |
| Read | `"\n"`, `"\r"`, `"\r\n"` | Only that ending splits lines, with no translation |
| Write | `None` (default) | `\n` becomes `os.linesep` |
| Write | `""` or `"\n"` | No translation |
| Write | `"\r"` or `"\r\n"` | `\n` becomes that string |
How the pieces connect
On writing, newline translation happens on the text, then encoding turns it into bytes. Reading reverses the order. Both steps are controlled by arguments to open(), so a single call can set both.
Edge cases
- Binary mode. With
"rb"or"wb", there is no encoding and no newline translation. You getbytes, and\r\nstays as two bytes. Passingencoding=together with a binary mode raisesValueError. splitlines()versus iterating a file.str.splitlines()splits on more boundaries than\n, including\r,\x0b,\x0c,\x1cto\x1e,\x85,\u2028, and\u2029. Iterating a text file splits only on the endings allowed bynewline. The two can disagree on the same text.- Normalization. The character
écan be one code point (\u00e9) orefollowed by a combining accent (\u0301). They look identical but compare unequal. Useunicodedata.normalize("NFC", s)before comparing text from different sources. - Standard streams.
sys.stdoutalso has an encoding. Printing a character the terminal encoding cannot represent raisesUnicodeEncodeError. When output is redirected on Windows, the encoding can differ from the console. Setting the environment variablePYTHONIOENCODING=utf-8overrides it. - File names. Names are encoded with the filesystem encoding, which is separate from the content encoding you pass to
open().
import unicodedata
a = "\u00e9"
b = "e\u0301"
print(a == b)
print(unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b))This prints False, then True.
A practical checklist
- Pass
encoding="utf-8"on every textopen()unless a format dictates something else. - Use
utf-8-sigwhen reading files that might come from Windows tools. - Leave
newlineat its default for ordinary text, and setnewline=""forcsv. - Keep the default
errors="strict"for data you must preserve, so problems surface at the source. - When you see
éstyle garbling, look for a UTF-8 file read as Latin-1 or a similar single-byte code page.
Exercise
A file data.csv was saved by a Windows program. When you read it with open("data.csv", encoding="utf-8"), the first column name prints as '\ufeffname' instead of 'name'. What is the cause, and what change to the open() call fixes it?
Show answer
The file starts with a UTF-8 byte order mark (bytes EF BB BF). The utf-8 codec keeps it as the character \ufeff. Opening the file with encoding="utf-8-sig" removes the BOM when decoding. If you pass the file to the csv module, also add newline="".
Exercise
You write f.write("a\nb\n") to a file opened with open("out.txt", "w", encoding="utf-8") on Windows, then read the file back with open("out.txt", "rb"). What bytes do you see, and how would you force Unix line endings on every platform?
Show answer
You see b'a\r\nb\r\n', because the default newline=None translates \n to os.linesep, which is \r\n on Windows. Open the file with newline="\n" to write the endings unchanged, which gives b'a\nb\n' on every platform.