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.

Introduction & Quick Summary
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start bytePython 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,zipfileorPIL. - 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 bytes | Likely format | Action |
|---|---|---|
1f 8b | gzip | gzip.decompress(data) |
50 4b 03 04 | zip / xlsx / docx | zipfile.ZipFile |
ff fe | UTF-16 LE with BOM | encoding="utf-16" |
ef bb bf | UTF-8 with BOM | encoding="utf-8-sig" |
89 50 4e 47 | PNG | binary mode |
25 50 44 46 | binary mode | |
| High bytes without a pattern | CP949 / Latin-1 / CP1252 | guess 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:
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 42raw = open("report.csv", "rb").read()
print(raw[:4].hex()) # inspect before decoding
text = raw.decode("cp949") # Korean CSV from ExcelFor pandas the same decision lives in the reader:
df = pd.read_csv("sales.csv", encoding="cp949")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 handler | Behavior | Safe for |
|---|---|---|
strict (default) | Raises | Anything you must not silently alter |
replace | U+FFFD per bad byte | Logs, terminal output |
ignore | Drops bytes | Nothing you plan to keep |
surrogateescape | Maps bytes to U+DC80–U+DCFF | Round-trip through a broken layer |
backslashreplace | \xNN text | Debugging |
errors="namereplace" | \N{...} | Rare, for documentation |
| Source of the error | Fix | Not 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 HTML | response.content.decode(charset) | response.text |
| Subprocess output | text=True, encoding=... | bytes.decode() on mixed data |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: The file is compressed
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:
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.
print("한글".encode("cp949").decode("latin-1"))
# — no exception, wrong textCase 3: requests and the charset header
r = requests.get(url)
text = r.text # uses header charset, falls back to ISO-8859-1When 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:
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:
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
subprocess.run(["git", "log"], capture_output=True, text=True)
# UnicodeDecodeError on a Windows console with a non-UTF-8 code pageSet the encoding and the error policy explicitly:
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
text = raw.decode("utf-8", errors="surrogateescape")
# ... pass through a text-only API ...
restored = text.encode("utf-8", errors="surrogateescape")
assert restored == rawsurrogateescape 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; passencoding=everywhere for reproducible behavior. PYTHONUTF8=1as 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.stdouton Windows. Printing characters the console code page cannot represent raisesUnicodeEncodeError(the encode direction);PYTHONIOENCODING=utf-8orsys.stdout.reconfigure(encoding="utf-8")fixes it.str.encodeerrors look similar.UnicodeEncodeErroris the mirror problem: the string is fine, the target codec cannot represent a character.chardet/charset-normalizeron 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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Handling Expired and Invalid Tokens with PyJWT in Python
Learn how to handle expired and invalid JWT tokens with PyJWT: catch ExpiredSignatureError, distinguish invalid tokens, and validate tokens safely in.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.