Sub topic 6
Encodings and Newlines
This chapter assumes you can use open() with the with statement, read and write text files, and tell str from bytes. It covers two settings that decide what ends up on disk: the encoding and the newline handling.
Why text mode needs an encoding
A file stores bytes. A str holds characters. In text mode, Python converts between them using an encoding, such as UTF-8, which maps each character to one or more bytes.
If you omit the encoding argument, Python uses a platform default. That default can differ between machines, so the same program may write a file on one computer that it cannot read on another. Always pass the encoding explicitly. For new files, use "utf-8".
text = "caf\u00e9"
with open("cafe.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("cafe.txt", "rb") as f:
print(f.read())The output is b'caf\xc3\xa9'. The character é takes two bytes in UTF-8. The other three characters take one byte each.
Encoding errors
If you read with the wrong encoding, you get one of two problems.
- A
UnicodeDecodeError, when the bytes are not valid in that encoding. - Garbled text called mojibake, when the bytes happen to be valid but map to different characters.
The next example reads the file from above as Latin-1, a single-byte encoding. Every byte is valid in Latin-1, so no error occurs, and the text comes out wrong.
with open("cafe.txt", encoding="latin-1") as f:
print(f.read())This prints café instead of café. Reading it as ASCII would raise an error instead.
try:
with open("cafe.txt", encoding="ascii") as f:
f.read()
except UnicodeDecodeError as exc:
print("decode failed:", exc.reason)The errors argument controls what Python does with bad data.
| Value | Behavior |
|---|---|
| `"strict"` | Raise an error. This is the default. |
| `"replace"` | Substitute a placeholder character such as `\ufffd`. |
| `"ignore"` | Drop the bad data silently. |
| `"backslashreplace"` | Write a Python-style escape for characters that cannot be encoded. |
If a file may start with a byte order mark (BOM), which some Windows tools add, read it with encoding="utf-8-sig". That codec removes the BOM when reading. Plain "utf-8" leaves it in the text as \ufeff.
Newline handling
Operating systems end lines differently. Unix and macOS use \n. Windows traditionally uses \r\n. Python hides this difference in text mode through the newline argument.
- Reading with the default
newline=None:\n,\r, and\r\nare all translated to\n. - Writing with the default
newline=None: each\nis translated toos.linesep, which is\r\non Windows and\nelsewhere.
So your code always uses \n, and Python adapts it to the platform.
To control the result yourself, pass newline explicitly.
with open("unix.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("one\ntwo\n")
with open("unix.txt", "rb") as f:
print(f.read())This prints b'one\ntwo\n' on every platform, because newline="\n" turns off translation on write.
| `newline` value | On read | On write |
|---|---|---|
| `None` (default) | Translate all endings to `\n` | `\n` becomes `os.linesep` |
| `""` | Lines split on any ending, no translation | No translation |
| `"\n"`, `"\r"`, `"\r\n"` | Split only on that ending, no translation | `\n` becomes that ending |
Use newline="" when you read or write CSV files. The csv module handles line endings itself, including line breaks inside quoted fields, and translation by Python would corrupt them.
Common mistakes
- Relying on the default encoding and getting different results on different systems.
- Reading a file with an encoding other than the one used to write it.
- Opening a file in binary mode and expecting
strvalues. Binary mode gives youbytesand does no decoding or newline translation. - Comparing lines without stripping the line ending, such as
line == "done"when the line is"done\n".
Exercise
You write the text "naïve\n" with open("a.txt", "w", encoding="utf-8"), then read the file back with open("a.txt", encoding="latin-1"). No exception is raised. What do you see, and why is there no error?
Show answer
You see garbled text, "naïve". In UTF-8, "ï" is stored as two bytes (0xC3 0xAF). Latin-1 maps every byte value to a character, so it decodes each byte separately as "Ã" and "¯" and never finds invalid data. Read the file with encoding="utf-8" to get the original text.
Exercise
On Windows, you write "a\nb\n" in text mode with the default newline setting. How many bytes does the file contain with the default setting, and how many if you pass newline="\n"?
Show answer
With the default, each "\n" becomes "\r\n", so the file has 6 bytes: a, \r, \n, b, \r, \n. With newline="\n", no translation happens and the file has 4 bytes.