Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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

The bytes are not UTF-8: gzip, CP949 Excel exports, UTF-16 with a BOM. Identify the signature, decode with the right codec, or treat it as binary.

~4 min readPython
#Python#Encoding#Unicode#Debugging
A Python byte stream crate rejected at a cyan UTF-8 gate, an amber encoding card and a gzip marker beside it

Introduction & Quick Summary

text
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

Python opened a byte stream, assumed UTF-8, and hit a byte that cannot appear in a valid UTF-8 sequence. The file is not corrupt: it is not text in the encoding you declared. 0x8b in position 1 after 0x1f is a gzip header; other common bytes point at Korean CP949, Latin-1 exports, or UTF-16 with a BOM.

The method is always the same — identify the bytes, then choose one of three responses:

  • Decode with the right codec. encoding="cp949", "utf-16", "latin-1", or let a library detect it.
  • Do not decode at all. If the payload is binary (gzip, zip, image), open it in binary mode and pass it to gzip, zipfile or PIL.
  • Decode lossily, deliberately. errors="replace" for logs and display, errors="surrogateescape" when the bytes must round-trip.

errors="ignore" is the one option to avoid: it silently deletes data and produces a file that looks fine until someone diffs it.

First bytesLikely formatAction
1f 8bgzipgzip.decompress(data)
50 4b 03 04zip / xlsx / docxzipfile.ZipFile
ff feUTF-16 LE with BOMencoding="utf-16"
ef bb bfUTF-8 with BOMencoding="utf-8-sig"
89 50 4e 47PNGbinary mode
25 50 44 46PDFbinary mode
High bytes without a patternCP949 / Latin-1 / CP1252guess from source system

Core Mechanics, Signatures & Reproducible Setup

bytes.decode("utf-8") validates the byte sequence against UTF-8's rules: continuation bytes must follow a lead byte of the right width, no overlong forms, no surrogates, nothing above U+10FFFF. Any violation raises UnicodeDecodeError with the codec name, the raw byte, the position and a one-line reason.

Text-mode file I/O does the same automatically. open(path) uses locale.getencoding() on Python 3.10+, which is UTF-8 on Linux, cp1252 on many Windows installs and cp949 on Korean Windows — a classic source of "works on my machine".

Reproduce each variant:

python
data = b"\x1f\x8b\x08\x00rest-of-gzip" data.decode("utf-8") # UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1 open("report.csv", encoding="utf-8").read() # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 42
python
raw = open("report.csv", "rb").read() print(raw[:4].hex()) # inspect before decoding text = raw.decode("cp949") # Korean CSV from Excel

For pandas the same decision lives in the reader:

python
df = pd.read_csv("sales.csv", encoding="cp949")
python
import gzip with gzip.open("events.jsonl.gz", "rt", encoding="utf-8") as f: for line in f: ...

gzip.open(..., "rt") decompresses and decodes in one step; passing the plain open() text mode instead is the mistake that produces the 0x8b error.

Key Comparison Table

Error handlerBehaviorSafe for
strict (default)RaisesAnything you must not silently alter
replaceU+FFFD per bad byteLogs, terminal output
ignoreDrops bytesNothing you plan to keep
surrogateescapeMaps bytes to U+DC80–U+DCFFRound-trip through a broken layer
backslashreplace\xNN textDebugging
errors="namereplace"\N{...}Rare, for documentation
Source of the errorFixNot a fix
Excel CSV (Korean)encoding="cp949"errors="ignore"
Excel CSV (Western)encoding="cp1252"latin-1 blindly
Notepad "Unicode"encoding="utf-16"stripping the BOM manually
requests HTMLresponse.content.decode(charset)response.text
Subprocess outputtext=True, encoding=...bytes.decode() on mixed data

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: The file is compressed

python
def read_log(path: str) -> str: with open(path, "rb") as f: head = f.read(2) if head == b"\x1f\x8b": with gzip.open(path, "rt", encoding="utf-8") as f: return f.read() with open(path, encoding="utf-8") as f: return f.read()

Sniffing two bytes is cheap and removes the guesswork. The same pattern covers .zip (zipfile.ZipFile(path).read(name).decode()), .bz2 and .xz.

Case 2: A CSV that came from Excel

Excel on Korean Windows writes CP949 by default when you choose "CSV (comma delimited)". Detection order that works in practice:

python
def decode_csv_bytes(raw: bytes) -> str: for enc in ("utf-8-sig", "cp949", "cp1252"): try: return raw.decode(enc) except UnicodeDecodeError: continue return raw.decode("utf-8", errors="replace")

Order matters: utf-8-sig handles a BOM and plain UTF-8, cp949 covers Korean Excel, cp1252 covers Western Excel. Do not add latin-1 before cp949 — it decodes every byte sequence without error and will silently mangle Korean text into mojibake.

python
print("한글".encode("cp949").decode("latin-1")) # — no exception, wrong text

Case 3: requests and the charset header

python
r = requests.get(url) text = r.text # uses header charset, falls back to ISO-8859-1

When a server omits Content-Type: ...; charset=utf-8, Requests historically fell back to ISO-8859-1 for text/*, producing mojibake rather than an exception. Decode explicitly:

python
r = requests.get(url) r.encoding = r.apparent_encoding or "utf-8" text = r.content.decode(r.encoding, errors="replace")

apparent_encoding runs chardet-style detection, which is good enough for HTML and unreliable for short payloads; for JSON use r.json() and let the parser work on bytes.

Case 4: Reading a file that is only partly UTF-8

Mixed-encoding files exist in older repositories: UTF-8 source with CP949 commit messages appended, or a log rotated across two locales. Decode line by line so one bad line does not kill the read:

python
def iter_lines(path: str): with open(path, "rb") as f: for i, line in enumerate(f, 1): try: yield line.decode("utf-8") except UnicodeDecodeError: yield line.decode("cp949", errors="replace")

This keeps the failure local and makes the odd line visible in output instead of aborting a 2 GB parse.

Case 5: Subprocess output

python
subprocess.run(["git", "log"], capture_output=True, text=True) # UnicodeDecodeError on a Windows console with a non-UTF-8 code page

Set the encoding and the error policy explicitly:

python
subprocess.run( ["git", "log"], capture_output=True, text=True, encoding="utf-8", errors="replace", )

On Windows, git output is often UTF-8 while the console code page is CP949; decoding as UTF-8 with replace keeps the log readable. When the bytes matter, collect them with text=False and decode at the point of use.

Case 6: Round-tripping bytes through a text layer

python
text = raw.decode("utf-8", errors="surrogateescape") # ... pass through a text-only API ... restored = text.encode("utf-8", errors="surrogateescape") assert restored == raw

surrogateescape is the only error handler that guarantees the original bytes survive a decode/encode cycle. It is the right choice for file paths from os.listdir on Linux, where filenames are byte strings that may not be UTF-8 at all.

Common Compilation/Runtime Mistakes & Version Gotchas

  • errors="ignore" in production. It converts a loud failure into silent data loss; a name field quietly loses a character and the bug surfaces months later.
  • Assuming open() is UTF-8. Python 3.15 moves the default to UTF-8 where the platform allows, but 3.10–3.14 still use the locale; pass encoding= everywhere for reproducible behavior.
  • PYTHONUTF8=1 as a global fix. It changes the default for files and stdio, which can break code that genuinely expects the locale encoding; prefer explicit arguments.
  • sys.stdout on Windows. Printing characters the console code page cannot represent raises UnicodeEncodeError (the encode direction); PYTHONIOENCODING=utf-8 or sys.stdout.reconfigure(encoding="utf-8") fixes it.
  • str.encode errors look similar. UnicodeEncodeError is the mirror problem: the string is fine, the target codec cannot represent a character.
  • chardet/charset-normalizer on short strings. Detection needs sample size; a 20-byte Korean string may be misidentified as Latin-1 with no error at all.

Decode a suspected byte sequence with the base64 tool after encoding it, so you can see exactly which bytes reach your parser, and convert a fixed CSV to JSON with the CSV to JSON converter once the encoding is right.

Primary references: codecs — Codec Base Classes documents error handlers and their guarantees, and Unicode HOWTO explains the encoding model behind these errors.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.