Sub topic 6
Encodings and newlines
This chapter assumes you can open, read, and write text files with open() and with. It also assumes you know the difference between str and bytes. Here you will learn how Python turns text into bytes and back, and how it handles line endings.
Text is not bytes
A disk stores bytes. A Python str is a sequence of Unicode characters. An encoding is the rule that maps characters to bytes and back. Opening a file in text mode adds a layer that applies this rule for you.
text = "café"
data = text.encode("utf-8")
print(data) # b'caf\xc3\xa9'
print(len(text), len(data)) # 4 5
print(data.decode("utf-8")) # café
print(text.encode("latin-1")) # b'caf\xe9'The same four characters give different bytes under different encodings. UTF-8 stores é as two bytes. Latin-1 stores it as one. If a file is written with one encoding and read with another, you get errors or garbled text.
print(b"caf\xc3\xa9".decode("latin-1")) # caféNo exception is raised there. Latin-1 maps every byte to some character, so it never fails, but the result is wrong. This kind of garbling is called mojibake.
Always pass `encoding`
If you call open("notes.txt") without encoding, Python uses a platform default. That default comes from the locale. On many Windows systems it has been a legacy code page such as cp1252. On Linux and macOS it is usually UTF-8. A script that works on your laptop can then fail on a colleague's machine, or silently write bytes that other tools misread.
Python is moving toward UTF-8 as the default on every platform (PEP 686, planned for Python 3.15). Until all your target versions have that change, pass the encoding explicitly:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("naïve café\n")
print(f.encoding) # utf-8The encoding attribute on a text file object shows what is in effect. To find places where you forgot the argument, run your program with python -X warn_default_encoding script.py. Python then emits an EncodingWarning for each open() call that relies on the default (available since Python 3.10).
Common encodings
| Encoding | Use it when | Notes |
|---|---|---|
| `utf-8` | Writing new files, exchanging data | Covers all of Unicode. ASCII text is byte-identical. |
| `utf-8-sig` | Reading or writing files that start with a byte order mark (BOM) | Strips the BOM on read, adds it on write. Some Windows tools expect it. |
| `utf-16` | A format or tool requires it | Writes a BOM and picks the byte order. Two or more bytes per character. |
| `latin-1` | Legacy Western European files, or when you must never fail | Decodes any byte, so it hides corruption. |
| `ascii` | You want to reject anything outside 0–127 | Raises on `é` and similar. |
A BOM is a short marker (\ufeff) at the start of a file. In UTF-8 it is not needed, but some programs, notably Excel for CSV files, add or expect it. If you read such a file as plain utf-8, the BOM stays in your data as an invisible first character:
with open("bom.txt", "w", encoding="utf-8-sig") as f:
f.write("hi")
with open("bom.txt", "rb") as f:
print(f.read()) # b'\xef\xbb\xbfhi'
with open("bom.txt", encoding="utf-8") as f:
print(repr(f.read())) # '\ufeffhi'
with open("bom.txt", encoding="utf-8-sig") as f:
print(repr(f.read())) # 'hi'A BOM often explains why the first key in a parsed header does not match what you expect.
When decoding fails
With the default settings, a byte sequence that is invalid for the chosen encoding raises UnicodeDecodeError. Text that cannot be represented raises UnicodeEncodeError on write. Both are subclasses of ValueError.
with open("legacy.txt", "wb") as f:
f.write(b"caf\xe9 au lait\n")
try:
with open("legacy.txt", encoding="utf-8") as f:
f.read()
except UnicodeDecodeError as exc:
print(exc)The message names the codec, the offending byte, and its position. Here the file is probably Latin-1 or cp1252, so the right fix is to use the right encoding. The errors argument is for cases where you cannot fix the source.
| `errors=` | Effect on read | Effect on write |
|---|---|---|
| `"strict"` (default) | Raises `UnicodeDecodeError` | Raises `UnicodeEncodeError` |
| `"replace"` | Bad bytes become `\ufffd` (�) | Unencodable characters become `?` |
| `"ignore"` | Bad bytes are dropped | Unencodable characters are dropped |
| `"backslashreplace"` | Bad bytes become `\xe9`-style text | Characters become `\u00e9`-style escapes |
| `"surrogateescape"` | Bad bytes become lone surrogate characters | Those surrogates turn back into the original bytes |
| `"xmlcharrefreplace"` | Not supported | Characters become `é`-style references |
with open("legacy.txt", encoding="utf-8", errors="replace") as f:
print(repr(f.read())) # 'caf\ufffd au lait\n'
with open("legacy.txt", encoding="latin-1") as f:
print(repr(f.read())) # 'café au lait\n'replace and ignore lose information permanently, so use them for display or logging, not for data you will save again. surrogateescape is the choice when you must pass unknown bytes through untouched. Read with it, process the text, and write with it, and the original bytes come back unchanged:
with open("legacy.txt", encoding="utf-8", errors="surrogateescape") as f:
text = f.read()
with open("legacy_copy.txt", "w", encoding="utf-8", errors="surrogateescape") as f:
f.write(text)
with open("legacy.txt", "rb") as a, open("legacy_copy.txt", "rb") as b:
print(a.read() == b.read()) # TrueThe in-memory string holds lone surrogates, which are not valid text. Do not send it to code that encodes strictly, such as a network library.
How line endings differ
Systems disagree on how to end a line:
- Unix, Linux, and modern macOS use
\n(LF). - Windows uses
\r\n(CRLF). - Classic Mac OS used
\r(CR). You will rarely meet it, but old files exist.
Python text mode hides this difference so that, inside your program, a line ends with \n. The newline argument of open() controls the translation, and it works differently on read and write.
Correction: the diagram must use the required fence form. Here it is.
Writing runs the same steps in reverse: newline translation first, then encoding.
The `newline` parameter
| `newline=` | On read | On write |
|---|---|---|
| `None` (default) | `\n`, `\r`, and `\r\n` all become `\n` | Each `\n` becomes `os.linesep` (`\r\n` on Windows, `\n` elsewhere) |
| `""` | Lines split on any of the three endings, but the text is returned untranslated | No translation |
| `"\n"` | Lines split on `\n` only, no translation | No translation |
| `"\r\n"` | Lines split on `\r\n` only, no translation | Each `\n` becomes `\r\n` |
| `"\r"` | Lines split on `\r` only, no translation | Each `\n` becomes `\r` |
Check what lands on disk by writing with one setting and inspecting the bytes:
with open("crlf.txt", "w", encoding="utf-8", newline="\r\n") as f:
f.write("one\ntwo\n")
with open("crlf.txt", "rb") as f:
print(f.read()) # b'one\r\ntwo\r\n'
with open("crlf.txt", encoding="utf-8") as f:
print(repr(f.read())) # 'one\ntwo\n'
with open("crlf.txt", encoding="utf-8", newline="") as f:
print(repr(f.read())) # 'one\r\ntwo\r\n'The default read translated the CRLF endings. With newline="" the original endings survive.
When to change the default
- Reproducible output. If a file must be byte-identical on every platform, write with
newline="\n". Otherwise Windows inserts\rbefore each line feed. Config files, generated source code, and test fixtures usually want this. - Preserving endings. Use
newline=""when you read a file and write it back and must not change its endings. A tool that rewrites a CRLF file should read and write withnewline="". - The
csvmodule. It requiresnewline=""on files you give it. It handles line endings itself, and it needs to see line breaks that occur inside quoted fields. Without it you can get blank lines between rows on Windows.
Pitfalls with newlines
Never write "\r\n" into a string yourself and then write it with the default settings on Windows. The \n is translated again, and you get \r\r\n.
Iterating over a file with newline="" splits on \n, \r, or \r\n. A string's splitlines() method splits on more than that, including \x0b, \x0c, \x1c to \x1e, \x85, \u2028, and \u2029. If a text contains those characters, text.splitlines() and list(file) give different results. Use file iteration when you want file semantics.
When you read with newline=None, the trailing \n is still part of each line. Use line.rstrip("\n") to remove it, as shown earlier in this tutorial. Do not use strip(), which also removes spaces you may want to keep.
Choosing settings: a checklist
- Pass
encoding="utf-8"unless a format or a consumer requires something else. - Leave
errorsat"strict"so corruption is reported. Relax it only with a stated reason. - Leave
newlineat its default for text you only use inside Python. Setnewline="\n"for files that must be identical everywhere, andnewline=""for CSV or when preserving endings. - If a file starts with a BOM, read it with
utf-8-sig. - If you are unsure of an encoding, open the file in
"rb"mode, look at the first bytes, and decide before choosing. Binary mode is covered in a later chapter.
Exercise
A file report.txt was saved on Windows with CRLF line endings. Your script reads it with open("report.txt", encoding="utf-8"), modifies one line, and writes it back with the same settings on Linux. What line endings does the output file have, and how do you keep the original CRLF endings?
Show answer
The default read converts \r\n to \n, and the default write on Linux leaves \n as it is, so the output has LF endings. To keep CRLF, open both the read and the write with newline="". Reading then returns \r\n untranslated, and writing then adds nothing and removes nothing, so the endings you read are the endings you write. Be sure any line you build yourself ends with \r\n.
Exercise
You read data.csv with encoding="utf-8" and the first header comes out as '\ufeffid' instead of 'id'. What is the cause, and what single change fixes it?
Show answer
The file begins with a UTF-8 byte order mark. Plain utf-8 keeps it as the character \ufeff at the start of the text. Open the file with encoding="utf-8-sig" (and newline="" since it is CSV), and the decoder removes the BOM.
Exercise
You must copy a text file of unknown encoding, changing only ASCII characters, and every other byte must survive unchanged. Which open() arguments do you use for reading and writing, and why?
Show answer
Use encoding="utf-8", errors="surrogateescape" on both the read and the write. Undecodable bytes become lone surrogates on read and turn back into the same bytes on write, so the round trip is lossless. The replace and ignore handlers would change or delete those bytes.