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

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))
```

## 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>`

## Sources

- [Python: Unicode HOWTO](https://docs.python.org/3/howto/unicode.html)
- [Python: open() built-in](https://docs.python.org/3/library/functions.html)
- [Python: codecs (standard encodings, error handlers)](https://docs.python.org/3/library/codecs.html)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/unicodedecodeerror
