Reading a Python UnicodeDecodeError
UnicodeDecodeError names the codec, the offending byte, and its zero-based position; the usual causes are a wrong encoding assumption, a truncated multi-byte sequence, or binary data. Read exc.encoding, exc.object, exc.start, exc.end, and exc.reason, inspect the bytes around the failure, then decode with the encoding the data actually uses.
The short answer
A UnicodeDecodeError means the bytes could not be interpreted with the codec you named. The exception carries five useful attributes: encoding (the codec attempted), object (the original bytes), start and end (the zero-based slice that failed), and reason (why it failed). The traceback prints the first bad byte in hex and its position, for example 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte. The data is either not UTF-8, truncated in the middle of a multi-byte sequence, or not text at all.
A minimal example
>>> b"caf\xe9!".decode("utf-8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
0xe9 is decimal 233, which is é in Latin-1 and Windows-1252 but is not valid UTF-8 on its own. In UTF-8, bytes 0x80 through 0xBF are continuation bytes and must follow a lead byte; 0xE9 is a lead byte for a three-byte sequence, so it expects two continuation bytes. The following ! is 0x21, not a continuation, hence the reason. The bytes almost certainly come from a Latin-1 or Windows-1252 file.
Truncation looks slightly different, because the sequence ends before it is complete:
>>> b"caf\xe9".decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of data
Inspect the exception programmatically instead of guessing:
from pathlib import Path
path = Path("notes.txt")
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError as exc:
raw = exc.object
print(exc.encoding, exc.start, exc.end, exc.reason)
print(raw[max(0, exc.start - 8): exc.end + 8])
Reading the message fields
| Field | Meaning |
|---|---|
encoding |
Codec that failed, for example utf-8 |
object |
The original bytes object |
start, end |
Zero-based slice of the offending byte or bytes |
reason |
Decoder's explanation, such as invalid start byte |
The position is a byte offset, not a character index, so it rarely matches an editor column; search the raw bytes around start for context.
Common causes
- Wrong encoding assumption. Windows-1252 or GBK text containing non-ASCII characters is not UTF-8.
latin-1decodes every byte sequence without error, which makes it a poor diagnostic: it hides the problem instead of proving the encoding. - Truncated sequence. A partial network read or interrupted write can leave a lead byte without its continuation bytes, so the error appears at the end of the data.
- Binary data. Reading a gzip stream or an image as text fails in the first bytes; check the magic number before decoding.
- UTF-16 read as UTF-8. The byte order mark produces
invalid start byte; useutf-16orutf-16-le.
A UTF-8 BOM is valid UTF-8 and never causes a decode error, but it can break parsers that compare the first key. Use utf-8-sig when you want it removed; see the UTF-8 BOM.
What changes the answer
The default encoding of open() and Path.read_text() is not guaranteed to be UTF-8: when encoding=None, Python uses the locale encoding unless UTF-8 mode is enabled. Code can therefore pass on one machine and fail on another. Pass encoding= explicitly at every boundary: files, subprocess with text=True, and anything that turns bytes into str.
Sockets always deliver bytes. Decode only after you know the charset, which for HTTP comes from Content-Type. For subprocess output, set both the codec and an error policy:
import subprocess
result = subprocess.run(
["git", "log", "--oneline"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
errors="replace" suits logs and display, not data you will parse, because it destroys the original bytes. errors="surrogateescape" round-trips unknown bytes back to bytes and is the right choice for filenames and pass-through pipelines.
Practical checks
- Print
sys.flags.utf8_modeandlocale.getpreferredencoding(False)to see whatencoding=Nonewill use. - Run
file -i pathfor a charset guess; treat it as a hint, not proof. - Decode a small prefix with candidate codecs and compare the result with known words in the text.
- On Python 3.7 and later,
-X utf8andPYTHONUTF8=1switch the default to UTF-8, which makes behaviour consistent across machines.
Sources
Revision history
- Published
- Updated
- — Initial publication.