Sub topic 1
Opening files safely: text mode, encodings, and newline handling
Every JSON and CSV file you read or write starts as a file opened with open(). Two settings in that call, encoding and newline, cause most of the bugs people hit later. This chapter explains what they do and which values to choose.
Prerequisites
This chapter assumes you can:
- Write basic Python syntax, including functions and
try/except. - Work with strings, lists, and dicts.
- Open a file with the
withstatement.
Text mode and binary mode
A file on disk holds bytes. Python's open() gives you one of two views of them:
| Mode | Example | You get |
|---|---|---|
| Text | `open(p, "r")` | `str` objects, decoded from bytes |
| Binary | `open(p, "rb")` | `bytes` objects, no decoding |
The json and csv modules work with text, so you will almost always use text mode. In text mode, Python decodes bytes to str on reading and encodes str to bytes on writing. An encoding is the rule for that translation.
Always name the encoding
If you leave out encoding, Python uses the platform default. That is often UTF-8 on Linux and macOS, but it can be something like cp1252 on Windows. Code that works on your machine can then fail or corrupt text on a colleague's machine. JSON is defined as UTF-8 in practice, and most CSV tools export UTF-8 too, so state it explicitly.
from pathlib import Path
path = Path("notes.txt")
with path.open("w", encoding="utf-8") as f:
f.write("Zürich\n")
with path.open("r", encoding="utf-8") as f:
print(f.read())Use with so the file is closed even if an error occurs. Closing flushes buffered writes to disk.
The most common error: wrong encoding
Reading a file with a different encoding than the one it was written in either raises UnicodeDecodeError or produces garbled text, called mojibake. This example writes Latin-1 bytes and then reads them as UTF-8.
from pathlib import Path
path = Path("legacy.txt")
path.write_bytes("Zürich".encode("latin-1"))
try:
path.read_text(encoding="utf-8")
except UnicodeDecodeError as e:
print("Decode failed at byte", e.start)
print(path.read_text(encoding="latin-1"))The byte 0xFC is ü in Latin-1 but is not valid UTF-8 on its own, so the first read fails at byte 1. The fix is to read with the encoding the file was actually written in. If you do not know it, ask the data's producer. Do not guess silently.
The errors parameter changes what happens on bad bytes. errors="replace" swaps them for a placeholder character, and errors="ignore" drops them. Both hide data loss, so use them only for logs or previews, not for data you will process.
The byte order mark
Some programs, notably Excel's "CSV UTF-8" export, put an invisible marker called a byte order mark (BOM) at the start of the file. Read with plain utf-8, the marker becomes the character \ufeff glued to your first header name, so a column called name shows up as '\ufeffname'. Use the utf-8-sig encoding when reading such files. It strips the BOM if present and works fine when it is absent.
with open("export.csv", encoding="utf-8-sig", newline="") as f:
print(f.readline())Newline handling
Line endings differ by system: Windows uses \r\n, Linux and macOS use \n. The newline parameter of open() controls how Python deals with this.
newline=None(the default): on reading,\r\nand\rbecome\n. On writing,\nbecomes the platform's line ending.newline="": no translation on writing. On reading, lines are split on any ending, but the original ending is kept.
with open("lines.txt", "w", newline="", encoding="utf-8") as f:
f.write("a\r\nb\r\n")
with open("lines.txt", newline="", encoding="utf-8") as f:
print(repr(f.read())) # 'a\r\nb\r\n'
with open("lines.txt", encoding="utf-8") as f:
print(repr(f.read())) # 'a\nb\n'Why the csv module needs newline=""
The csv module handles line endings itself. A quoted CSV field may contain a line break, and the module must see the original characters to treat it correctly. If you leave newline at its default, you can get extra blank lines between rows on Windows, or damaged multi-line fields. The csv documentation says to open files with newline="", so the later CSV chapters always do.
For JSON, line endings are just whitespace, so the default newline is fine.
A safe opening checklist
- Use
withto open every file. - Pass
encoding="utf-8"for reading and writing, orutf-8-sigfor files that may start with a BOM. - Add
newline=""when the file goes to thecsvmodule. - When you see
UnicodeDecodeError, find out the real encoding instead of suppressing errors.
Exercise
A colleague on Windows opens a CSV file you wrote with open("data.csv", "w") and passes it to csv.writer. Their output has a blank line after every row. Which open() argument is missing, and what other argument should you add so that accented names are stored the same way on every machine?
Show answer
Add newline="" to stop Python from translating line endings a second time, which causes the blank lines. Add encoding="utf-8" so the text is encoded the same way on every platform. The call becomes open("data.csv", "w", newline="", encoding="utf-8").