GrepBoard/Manuals
605 manuals ·

Fix UnicodeDecodeError: 'utf-8' codec can't decode byte

·Tested on Python 3.12.16 (Docker python:3.12-slim) · 2026-10·Test scope ↓·6 steps

UnicodeDecodeError 'utf-8' codec can't decode byte means a non-UTF-8 file was read as UTF-8. Use the byte value to spot cp1252, a BOM or gzip; set encoding=.

output
Traceback (most recent call last):  File "<string>", line 1, in <module>  File "<frozen codecs>", line 322, in decodeUnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 13: invalid continuation byte

Python tried to decode bytes that are not UTF-8 as UTF-8. A typical case is a CSV saved as Windows-1252 (cp1252) opened on Linux with a plain open(). **Put the file's real encoding in encoding=** and it reads. The output above is a cp1252 file containing René read with no encoding.

[1] Read the byte 0x.. and position in the error line. They narrow the cause a lot. These came up in testing:

Error lineFile
byte 0xe9 in position 13: invalid continuation byteRené saved as cp1252 (accented letters not in UTF-8 form)
byte 0xc0 in position 0: invalid start byteKorean CSV saved as cp949 (first character non-ASCII)
byte 0x8b in position 1: invalid start byteA gzip file opened as text
byte 0xff in position 0: invalid start byteA UTF-16 file (first two bytes ff fe)

position is the offset inside the chunk of bytes the decoder was given (the exception's start). When a small file is read in one read(), as in the table above, that equals the offset from the start of the file; when a large file is read with for line in f, Python decodes it internally in fixed-size chunks and counting restarts with each one, so it differs from the file offset. 0 means the first byte of that chunk is not UTF-8; what came before it may be ASCII or perfectly valid multi-byte UTF-8. If you need the exact spot, print e.start, e.end and e.object[e.start:e.end] from the exception.

[2] Look at the bytes around that position. Binary mode ("rb") does not decode, so it never raises this error.

console
$ python -c 'b = open("data.csv", "rb").read(); print(b[3:23])'
output
b'e,city\nRen\xe9,Z\xfcrich\n'

é is the single byte \xe9 and ü is \xfc. In UTF-8 those letters take two bytes each, so single high bytes between ASCII letters point to cp1252 or Latin-1.

[3] Read with the right encoding. For Western European text from Windows, use **cp1252** rather than latin-1.

console
$ python -c 'print(open("data.csv", encoding="cp1252").read())'
output
name,cityRené,Zürich

latin-1 also read that file, but it never fails, so it hides mistakes. It maps the bytes cp1252 uses for € and curly quotes to invisible control characters:

console
$ python -c 'print(open("price.txt", encoding="cp1252").read())'$ python -c 'print(repr(open("price.txt", encoding="latin-1").read()))'
output
Price: €5 “net”'Price: \x805 \x93net\x94\n'

csv.reader and json.load read whatever file object open() gives them, so fix it at open(…, encoding="cp1252").

[4] No error but a strange first column name means a BOM. UTF-8 saved with a BOM (ef bb bf) at the start decodes as utf-8, but the first header gets \ufeff stuck to it and row["id"] raises KeyError.

console
$ python -c 'import csv; print(next(csv.DictReader(open("bom.csv", encoding="utf-8"))))'$ python -c 'import csv; print(next(csv.DictReader(open("bom.csv", encoding="utf-8-sig"))))'
output
{'\ufeffid': '1', 'name': 'a'}{'id': '1', 'name': 'a'}

utf-8-sig strips a BOM if there is one and otherwise reads like utf-8. If the first two bytes are ff fe, the file is UTF-16: use encoding="utf-16". A gzip file (1f 8b) is not text; open it with gzip.open(path, "rt", encoding="utf-8").

[5] Do not silence it with errors="replace" or "ignore". The error goes away and the characters go with it.

console
$ python -c 'print(open("data.csv", encoding="utf-8", errors="replace").read())'
output
name,cityRen�,Z�rich

Save that result and the original letters are gone for good. Use it only for something like a log where a few bytes are genuinely corrupt, and even then only read — keep the source file untouched.

[6] Prevent it next time: convert the file to UTF-8, and have the writing side name its encoding too. Write the converted file under a new name, check it, then swap it in.

console
$ iconv -f CP1252 -t UTF-8 price.txt > price.utf8.txt && python -c 'print(open("price.utf8.txt", encoding="utf-8").read())'
output
Price: €5 “net”

When open() has no encoding, Python up to 3.14 uses locale.getencoding() if UTF-8 Mode is off (with UTF-8 Mode on, it uses UTF-8). That was UTF-8 in the tested Linux container, but on a machine with a different locale (Windows, for example) the value differs, and the same code then fails the other way round, reading a UTF-8 file with the locale encoding. locale.getencoding() ignores UTF-8 Mode, so its value alone can mislead. On the machine that runs the code, check both with python -c 'import sys, locale; print(sys.flags.utf8_mode, locale.getencoding())' (a first value of 1 means UTF-8 Mode), and for certainty print f.encoding on the file object your code opens. From Python 3.15, UTF-8 Mode is on by default (PEP 686). On any version, writing encoding="utf-8" on both reads and writes keeps results the same everywhere.

If the error comes during a pip install instead, see pip No matching distribution found or pip subprocess-exited-with-error.

#python#unicode#encoding#cp1252#csv