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 byteQuick 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.
- Inspect the first bytes: open(path, 'rb').read(4) or xxd file | head -1.
- FF FE or FE FF means UTF-16: pass encoding='utf-16'.
- FF D8 is a JPEG and 89 50 4E 47 a PNG: read with 'rb'.
- EF BB BF is UTF-8 with a BOM: use encoding='utf-8-sig'.
- For legacy Windows exports, try encoding='cp1252' and spot-check accented characters.
- Use errors='replace' only where losing a few characters is acceptable.
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))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.
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
- ModuleNotFoundError: No module named 'x'
- TypeError: 'NoneType' object is not subscriptable
- SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
More in JSON, parsing and validation
- SyntaxError: Unexpected end of JSON inputNode.js
- TypeError: Converting circular structure to JSONNode.js
- ZodError: [ { "expected": "string", "code": "invalid_type", "path": [ "email" ]...Node.js
- RangeError: Invalid time valueNode.js
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)Python
- TypeError: Object of type datetime is not JSON serializablePython
- pydantic_core._pydantic_core.ValidationError: 1 validation error for User email Field...Python
Other error topics
- BrokenPipeError: [Errno 32] Broken pipeNetwork and HTTP
- Error: read ECONNRESETNetwork and HTTP
- Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com'...Network and HTTP
- MongoServerError: E11000 duplicate key error collection: app.users index: email_1 dup...Databases
- psycopg.errors.UndefinedColumn: column "titel" does not existDatabases
- sqlite3.OperationalError: database is lockedDatabases
- Error: Cannot find module 'x'Imports and modules
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Imports and modules
- ImportError: libGL.so.1: cannot open shared object file: No such file or directoryImports and modules
- ChunkLoadError: Loading chunk 4512 failed. (error...React and Next.js rendering
- Only plain objects, and a few built-ins, can be passed to Client Components from Server...React and Next.js rendering
- useSearchParams() should be wrapped in a suspense boundary at page "/search".React and Next.js rendering
- IndexError: list index out of rangeUndefined, None and type errors
- System.InvalidOperationException: Sequence contains no elementsUndefined, None and type errors
- TypeError: Client is not a constructorUndefined, None and type errors
- Error: EMFILE: too many open files, open '/app/uploads/0412.jpg'Memory, async and the process
- FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memoryMemory, async and the process
- OSError: [Errno 98] Address already in useMemory, async and the process
- Not Acceptable: Client must accept both application/json and text/event-streamMCP servers and clients
- Bad Request: Unsupported protocol version: 2026-07-28MCP servers and clients
- MCP error -32602: Input validation error: Invalid arguments for tool get_orderMCP servers and clients
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.