How do you solve "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff"? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you solve "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff"?

message-square
0

Open the file with the true source encoding instead of UTF-8—most commonly encoding="utf-16" (or encoding="utf-8-sig" for UTF-8 with BOM) when byte 0xff appears at position 0 (a UTF-16LE Byte Order Mark FF FE), or encoding="cp1252" / encoding="latin-1" for legacy Windows single-byte files—and pass errors="replace" only when recovering corrupted mixed-encoding text.

Basic Example

from pathlib import Path

file_path = Path("export.csv")

# 1. Recommended when byte 0xff is at position 0 (UTF-16LE BOM `FF FE`, common from Windows/Excel/PowerShell):
with open(file_path, "r", encoding="utf-16") as f:
    text = f.read()

# 2. Recommended for legacy Western Windows text/CSV files (where 0xff represents 'ÿ'):
with open(file_path, "r", encoding="cp1252") as f:
    win_text = f.read()

# 3. Fallback for partially corrupted logs where dropping invalid bytes is acceptable:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
    safe_text = f.read()  # Invalid bytes become '' instead of crashing

Key Details & Edge Cases

  • Inspect the byte offset (in position X) to diagnose the exact encoding immediately:
    • in position 0 (0xff 0xfe ...): Byte 0xff followed by 0xfe at index 0 is the UTF-16 Little-Endian Byte Order Mark (BOM)—generated by PowerShell >, Windows Notepad, SQL Server exports, and Excel Unicode Text. Open with encoding="utf-16" (which automatically strips the BOM and decodes both LE and BE).
    • in position > 0 (mid-file): Byte 0xff inside body text is usually cp1252 / iso-8859-1 (latin-1) (where 0xff is ÿ) or a binary file (.xlsx, .zip, .gz, .jpg, .pyc) accidentally opened in text mode ("r" instead of "rb").
  • Inspect the raw header bytes before guessing (Path.read_bytes()):
    • Check the first 16 raw bytes in Python to identify BOM signatures or binary magic headers:
      raw = Path("export.csv").read_bytes()[:16]
      print(raw)
      # b'\xff\xfe...' -> UTF-16LE  |  b'\xfe\xff...' -> UTF-16BE
      # b'\xef\xbb\xbf' -> UTF-8-SIG |  b'PK\x03\x04' -> ZIP / .xlsx (use pd.read_excel!)
      
  • Pandas pd.read_csv() equivalent (encoding= & encoding_errors=):
    • In Pandas, pass pd.read_csv("export.csv", encoding="utf-16") (often paired with sep="\t" for Excel/PowerShell UTF-16 exports) or pd.read_csv("export.csv", encoding="cp1252")—and use encoding_errors="replace" in Pandas 1.3+ when cleaning messy CSVs.
  • Why encoding="latin-1" never raises UnicodeDecodeError (and why to use it carefully):
    • latin-1 (iso-8859-1) maps every possible byte 0x00–0xff 1-to-1 to Unicode code points U+0000–U+00FF. While it never crashes, decoding UTF-16 or UTF-8 text with latin-1 produces mojibake ("h\x00e\x00l\x00l\x00o\x00" or "é"), so only use latin-1 when the source data is genuinely single-byte ISO-8859-1.

Comparison of Fixes for UnicodeDecodeError on Byte 0xff

Cause / Symptom Open / Read Fix Byte Signature Best Used When
UTF-16LE / UTF-16BE File open(p, encoding="utf-16") Starts with b"\xff\xfe" or b"\xfe\xff" (position 0) Files exported from Windows PowerShell, SQL Server, or Excel Unicode Text.
Windows Western Legacy Text open(p, encoding="cp1252") Contains 0xff (ÿ), 0x93/0x94 (smart quotes), 0x80 (€) Legacy Windows CSVs, logs, or European text files.
Corrupted / Mixed-Encoding Text open(p, encoding="utf-8", errors="replace") Sporadic invalid bytes in otherwise valid UTF-8 Scraping messy web pages or reading partially corrupted log files.
Binary File Opened as Text open(p, "rb") or pd.read_excel(p) Starts with b"PK\x03\x04", b"\x1f\x8b", etc. Reading .xlsx, .zip, .gz, images, or serialized binary artifacts.
Unknown File Encoding charset_normalizer.from_path(p).best() Variable Auto-detecting encodings across arbitrary user-uploaded text files.