Sub topic 1
Opening files safely: text mode, encodings, and newline handling
Prerequisites
This chapter assumes you can:
- Write basic Python: variables, loops, and f-strings.
- Work with strings, lists, and dicts.
- Open a file with a
withstatement. - Write a function and catch an exception with
tryandexcept.
Everything else is introduced here. The JSON and CSV modules in later chapters build on the habits from this one.
Why file opening deserves its own chapter
Most bugs in JSON and CSV code come from how the file was opened, not from the parsing. Three settings decide whether text survives a round trip:
- The mode (text or binary).
- The encoding.
- The newline handling.
A file is a sequence of bytes. Python text is a sequence of characters. An encoding is the rule that converts between the two. When you open a file in text mode, Python applies that rule for you on every read and write. If it picks the wrong rule, you get garbled characters or an exception.
Text mode and binary mode
open() returns different kinds of objects depending on the mode.
| Mode | Reads or writes | Decoding | Typical use |
|---|---|---|---|
| `"r"` (default) | `str` | Yes, using the encoding | Reading JSON, CSV, and other text |
| `"w"` | `str` | Yes, truncates the file first | Writing text, replacing old content |
| `"a"` | `str` | Yes, appends to the end | Logs, JSON Lines |
| `"x"` | `str` | Yes, fails if the file exists | Never overwrite by accident |
| `"rb"`, `"wb"` | `bytes` | None | Images, archives, raw inspection |
The json and csv modules work with text, so you will almost always use text mode. Binary mode is still useful for one thing: looking at exactly what is stored on disk.
from pathlib import Path
path = Path("greeting.txt")
path.write_text("Zürich\n", encoding="utf-8")
print(path.read_text(encoding="utf-8")) # Zürich
print(path.read_bytes()) # b'Z\xc3\xbcrich\n' on Linux and macOSThe character ü is stored as two bytes, \xc3\xbc. On Windows, write_text also converts \n to \r\n, so the last byte sequence differs. The newline section below explains why.
Encodings
What the default encoding is
If you call open("data.txt") without an encoding argument, Python uses the platform's preferred encoding. You can see it with locale.getpreferredencoding(False). On most Linux and macOS systems it is UTF-8. On many Windows systems it is a legacy code page such as cp1252.
This means the same script can work on your laptop and fail on a colleague's machine. Python 3.15 changes the default to UTF-8 (PEP 686), but code that must run on older versions should not rely on that.
To find places where you forgot, run your script with python -X warn_default_encoding script.py. Python 3.10 and later then emits an EncodingWarning for each open() call that relies on the default.
What a mismatch looks like
A mismatch fails in one of two ways. Either Python raises an error, or it silently produces wrong text.
data = "Zürich".encode("utf-8")
try:
data.decode("ascii")
except UnicodeDecodeError as e:
print(e)
# 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
print(data.decode("latin-1")) # ZürichThe latin-1 decoding does not fail, because every byte value is a valid Latin-1 character. The result is mojibake: readable-looking text that is wrong. Mojibake is harder to catch than an exception, because no error tells you something went wrong.
The reverse problem exists on writing. If you write "Zürich" with encoding="ascii", Python raises UnicodeEncodeError, because ü has no ASCII representation.
The `errors` parameter
open() accepts an errors argument that controls what happens to bytes or characters that cannot be converted.
| Value | Behavior |
|---|---|
| `"strict"` (default) | Raise `UnicodeDecodeError` or `UnicodeEncodeError` |
| `"replace"` | Substitute `\ufffd` (�) when reading, `?` when writing |
| `"ignore"` | Drop the problem data silently |
| `"backslashreplace"` | Write a `\xNN` or `\uNNNN` escape instead |
raw = b"Z\xfcrich" # Latin-1 bytes, not valid UTF-8
print(raw.decode("utf-8", errors="replace")) # Z�rich
print(raw.decode("latin-1")) # ZürichKeep "strict" as the default for data you care about. "replace" and "ignore" hide damage, and data loss that nobody notices is worse than a loud crash. If you know the file is in another encoding, name that encoding explicitly instead.
Byte order marks
A byte order mark (BOM) is a few bytes at the start of a file that announce its encoding. UTF-8 does not need one, but some programs add it anyway. Excel on Windows is a common source: its "CSV UTF-8" export begins with the three bytes \xef\xbb\xbf.
If you read such a file as plain utf-8, the BOM becomes an invisible first character, \ufeff. In a CSV file, that character ends up glued to the first column name, so row["id"] raises KeyError because the key is actually "\ufeffid".
from pathlib import Path
path = Path("bom.txt")
path.write_text("id,name\n", encoding="utf-8-sig")
print(path.read_bytes()[:3]) # b'\xef\xbb\xbf'
print(repr(path.read_text(encoding="utf-8")[:2])) # '\ufeffi'
print(repr(path.read_text(encoding="utf-8-sig")[:2])) # 'id'The utf-8-sig codec removes a BOM when reading if one is present. When reading, it works on files with or without a BOM. When writing, it always adds one, so use it for output only when you know the consumer, such as Excel, needs it.
The json module also refuses a string that starts with a BOM. It raises a JSONDecodeError whose message says Unexpected UTF-8 BOM (decode using utf-8-sig). Opening with utf-8-sig fixes that too.
Newline handling
Operating systems disagree about how to end a line. Unix, Linux, and modern macOS use \n. Windows uses \r\n. Very old Mac files use \r. Python hides this difference in text mode, and the newline argument of open() controls how.
Reading
| `newline=` | What reading does |
|---|---|
| `None` (default) | Treats `\n`, `\r`, and `\r\n` as line ends and converts all of them to `\n` |
| `""` | Treats all three as line ends, but returns them unchanged |
| `"\n"`, `"\r"`, `"\r\n"` | Splits lines only on that one ending, returned unchanged |
Writing
| `newline=` | What writing does |
|---|---|
| `None` (default) | Converts each `\n` to `os.linesep` (`\r\n` on Windows, `\n` elsewhere) |
| `""` or `"\n"` | Writes `\n` unchanged |
| `"\r\n"`, `"\r"` | Converts each `\n` to that string |
You can see the read behavior by writing raw bytes and reading them back in two ways.
from pathlib import Path
path = Path("mixed.txt")
path.write_bytes(b"a\r\nb\rc\n")
with path.open(encoding="utf-8") as f:
print(repr(f.read())) # 'a\nb\nc\n'
with path.open(encoding="utf-8", newline="") as f:
print(repr(f.read())) # 'a\r\nb\rc\n'With the default, the three different endings become \n and the file looks uniform. With newline="", you see the original endings.
For ordinary text files, the default is convenient. For files you want to be identical on every platform, such as JSON or JSON Lines you commit to version control, pass newline="\n" when writing.
from pathlib import Path
with open("out.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("x\ny\n")
print(Path("out.txt").read_bytes()) # b'x\ny\n' on every platformWhy the csv module needs `newline=""`
The csv module does its own line-ending handling, and it expects to see the raw endings. A CSV writer ends each row with \r\n by default (the lineterminator setting). If you open the output file with the default newline=None on Windows, Python then converts the \n in that \r\n to \r\n again, and the file ends up with \r\r\n. Many programs display that as a blank line after every row.
Reading has a related problem. A quoted CSV field may legitimately contain a line break. If the file is opened with the default, Python rewrites that break before the csv module sees it, which changes your data. With newline="", the reader receives the bytes as stored and decides for itself what is a row end and what is data.
import csv
rows = [["id", "note"], ["1", "line one\nline two"]]
with open("notes.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
with open("notes.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
# ['id', 'note']
# ['1', 'line one\nline two']The json module has no such requirement, because JSON treats line breaks between values as ordinary whitespace and encodes line breaks inside strings as \n escapes.
A decision guide
The diagram shows how to choose the arguments for the files you will meet in this tutorial.
Putting it together
Here is a short helper that reads a text file safely and reports a bad encoding clearly. It uses only what this chapter covered.
from pathlib import Path
def read_text_file(path):
path = Path(path)
try:
with path.open(encoding="utf-8-sig") as f:
return f.read()
except FileNotFoundError:
raise SystemExit(f"File not found: {path}")
except UnicodeDecodeError as e:
raise SystemExit(
f"{path} is not valid UTF-8 (byte {e.start}: {e.reason}). "
"Check which encoding the file was saved in."
)
Path("sample.txt").write_text("café\n", encoding="utf-8")
print(read_text_file("sample.txt"), end="") # caféUsing utf-8-sig for reading is safe here, because it accepts files with and without a BOM. The UnicodeDecodeError object carries start (the byte offset) and reason, which give the user something specific to act on.
Common mistakes
- Omitting
encoding. The script works on your machine and fails elsewhere. Always name the encoding. - Using
errors="ignore"to silence a decode error. The error is telling you the encoding is wrong. Find the right one instead. - Opening a CSV file without
newline="". You get blank rows on Windows and altered multi-line fields everywhere. - Reading an Excel export with plain
utf-8. The first header gets a hidden\ufeffprefix. Useutf-8-sig. - Opening in
"w"mode on a file you meant to keep. The file is truncated the momentopen()returns. Use"x"to refuse to overwrite, or"a"to append. - Mixing binary and text. Passing a file opened with
"wb"tojson.dumpfails with aTypeError, becausejson.dumpwritesstr, notbytes.
Exercise
A colleague sends you a CSV file exported from Excel. Your script opens it with open("data.csv", newline="", encoding="utf-8") and uses csv.DictReader, but row["id"] raises KeyError even though the header row visibly starts with id. What is the likely cause, and what one-word change to the open() call fixes it?
Show answer
The file starts with a UTF-8 byte order mark. Reading it as plain utf-8 leaves the invisible character \ufeff at the start of the first header, so the real key is "\ufeffid". Changing the encoding argument to "utf-8-sig" strips the BOM, and row["id"] then works.
Exercise
You write a CSV file on Windows with open("out.csv", "w", encoding="utf-8") and csv.writer. The file shows a blank line after each row in some programs. Why does this happen, and how do you fix it?
Show answer
The csv writer ends each row with \r\n. Because newline was not set to "", Python's text layer converts the \n in that sequence to \r\n again on Windows, producing \r\r\n. Opening the file with newline="" turns that conversion off, so each row ends with a single \r\n.
Exercise
What does Python return when you read the bytes b"a\r\nb\n" with open(path, encoding="utf-8") compared with open(path, encoding="utf-8", newline="")?
Show answer
With the default newline=None, the result is 'a\nb\n', because \r\n is translated to \n. With newline="", the result is 'a\r\nb\n', because the original line endings are returned unchanged.