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

Python · updated 2026-11-12

Raised when Python decodes bytes as UTF-8: reading a file opened in text mode, calling bytes.decode(), or loading a CSV with pandas. The byte and position are clues; 0xff at position 0 is the start of a UTF-16 byte order mark or a JPEG header.

Traceback (most recent call last):
  File "/srv/app/import_contacts.py", line 9, in <module>
    for row in csv.reader(f):
  File "<frozen codecs>", line 322, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Quick fix

Open the file with the encoding it was written in. Byte 0xff at position 0 is typically the UTF-16 little-endian byte order mark (FF FE), so use open(path, encoding='utf-16'). If the file is binary, like an image or an archive, open it with 'rb' and don't decode it at all.

  1. Inspect the first bytes: open(path, 'rb').read(4) or xxd file | head -1.
  2. FF FE or FE FF means UTF-16: pass encoding='utf-16'.
  3. FF D8 is a JPEG and 89 50 4E 47 a PNG: read with 'rb'.
  4. EF BB BF is UTF-8 with a BOM: use encoding='utf-8-sig'.
  5. For legacy Windows exports, try encoding='cp1252' and spot-check accented characters.
  6. Use errors='replace' only where losing a few characters is acceptable.
python
import csv

with open(path, "rb") as f:
    head = f.read(4)

if head.startswith((b"\xff\xfe", b"\xfe\xff")):
    encoding = "utf-16"
elif head.startswith(b"\xef\xbb\xbf"):
    encoding = "utf-8-sig"
else:
    encoding = "utf-8"

with open(path, encoding=encoding, newline="") as f:
    rows = list(csv.reader(f))
Fix it with your coding agent

Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.

prompttext
Read https://runheed.com/errors/unicodedecodeerror.md and fix this error in this project.

Why it happens

The file is UTF-16

Excel's Unicode Text export, Windows PowerShell 5.1 output redirection (> out.txt) and some database tools write UTF-16 with a byte order mark. A leading 0xff or 0xfe at position 0 is the giveaway; decoding as UTF-16 fixes it.

A binary file opened in text mode

Images, archives and pickles are not text. A JPEG starts with FF D8, so it fails with exactly this byte at position 0; a PNG fails on 0x89 at position 0 and a gzip file on 0x8b at position 1. Open these with rb.

Legacy 8-bit encoding

cp1252 or Latin-1 text from older Windows tools decodes fine until the first accented character, then fails with 'invalid continuation byte' at some later position. Ask where the file came from, or test cp1252 against known names.

Decoding raw HTTP bytes yourself

urllib returns still-compressed bytes if the request asked for gzip, and many sites serve charsets other than UTF-8. Check Content-Encoding and the charset in Content-Type before calling .decode() on a response body.

Spreadsheet read as CSV

pd.read_csv on an .xlsx or .xls file reads a binary workbook as text and fails on the first non-UTF-8 byte. Use pd.read_excel for workbooks, and read_csv only on real CSV exports.

Other fixes

  • Use errors='replace' or errors='backslashreplace' for logs and best-effort reads where a few garbled characters are fine.
  • For files of unknown origin, detect the encoding with the charset-normalizer package, then store the result as UTF-8.
  • In pandas, pass encoding='utf-16' and sep='\t' to read_csv for Excel Unicode Text exports.
  • A different error with a similar name: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes ... truncated \UXXXXXXXX escape. Python read a Windows path such as "C:\Users\..." in a normal string, where \U starts an escape. Write the path as a raw string (r"C:\Users\..."), with forward slashes, or with doubled backslashes.

Same error, other wording

  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12: invalid continuation byte
  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
  • UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1234: character maps to <undefined>

Let your coding agent catch the next one

Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:

> Find the UnicodeDecodeError events in production, show which reader raised each one and the byte it failed on, and make that reader detect UTF-16 and binary input instead of assuming UTF-8.

Setup for Flask, Python and FastAPI or Django, then have your agent fix and resolve it.

Related errors

More in JSON, parsing and validation

Other error topics

Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.

References: Python: Unicode HOWTO, Python: open() built-in, Python: codecs (standard encodings, error handlers)

Spotted a mistake? Email hello@greatwork.company. About Runheed.