Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12: invalid continuation byte
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
- UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1834: character maps to <undefined>
- UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 47: invalid start byte
Python reads the file as UTF-8 while it was saved in another encoding, most often Windows-1252 (cp1252) or Latin-1: byte 0xe9 is an “é” in those encodings. Pass the right encoding when reading, for example open(path, encoding="cp1252") or pd.read_csv(path, encoding="cp1252"), or convert the file to UTF-8.
What this error means
A text file is just a sequence of bytes: to get characters, Python must decode them with an encoding. In UTF-8, “é” takes two bytes (0xc3 0xa9), while in cp1252 or Latin-1 it is a single byte, 0xe9. In UTF-8, 0xe9 announces a three-byte sequence: if the next byte is not a valid continuation byte, the decoder stops with “invalid continuation byte”. The position shown is the index of the faulty byte in the chunk being read. So the error does not come from your data, but from a mismatch between the file’s real encoding and the one used to read it.
Common causes
- File saved as Windows-1252 or Latin-1: Excel CSV export (plain “CSV” format), legacy business software, file created on Windows with an older Notepad.
- Platform default encoding: without
encoding=,open()uses the locale encoding. On Windows it is often cp1252, hence the'charmap' codec can't decodeerror on a file that is actually UTF-8. - UTF-16 file:
byte 0xff in position 0: invalid start bytealmost always means a UTF-16 byte order mark (FF FE), typical of a>redirect in Windows PowerShell 5.1. - Binary file read as text: an image, PDF,
.xlsxor compressed file opened in text mode or passed toread_csv. - File mixing several encodings: files of different origins concatenated, data pasted from several sources.
Step-by-step fix
-
Identify the file’s real encoding
The
filecommand gives a first hint (-Ion macOS,-ion Linux). On every system,charset-normalizer(already installed withrequests) guesses the most likely encoding.# macOS file -I data.csv # Linux file -i data.csv # any OS python -m pip install charset-normalizer normalizer data.csv -
Set the encoding in open()
Always pass
encoding=explicitly. For a Windows or Excel file, prefercp1252overlatin-1: both read “é”, but only cp1252 decodes€,’orœcorrectly. For UTF-8 with a BOM (Excel “CSV UTF-8”, Notepad), useutf-8-sig.with open("data.csv", encoding="cp1252") as f: text = f.read() # UTF-8 file with a BOM with open("export.csv", encoding="utf-8-sig") as f: text = f.read() # UTF-16 file (starts with bytes FF FE) with open("report.txt", encoding="utf-16") as f: text = f.read() -
Fix pandas.read_csv
read_csvreads UTF-8 by default. Pass the detected encoding and, for a European Excel export, the;separator. An.xlsxfile is read withread_excel, notread_csv.import pandas as pd df = pd.read_csv("data.csv", encoding="cp1252", sep=";") # Excel "CSV UTF-8" export df = pd.read_csv("export.csv", encoding="utf-8-sig") # real Excel workbook (pip install openpyxl) df = pd.read_excel("data.xlsx") -
Read binary files in binary mode
If the file is not text (image, PDF, archive), open it with
"rb": you getbytesand no decoding happens. For an HTTP response, useresponse.contentfor bytes andresponse.textfor decoded text.with open("photo.jpg", "rb") as f: data = f.read() print(len(data), data[:4]) -
Convert the file to UTF-8 once and for all
Rather than handling the encoding everywhere, convert the source file. In Python it works on every OS; on macOS and Linux,
iconvdoes the same.from pathlib import Path src = Path("data.csv") text = src.read_text(encoding="cp1252") src.with_name("data-utf8.csv").write_text(text, encoding="utf-8") # macOS / Linux alternative: # iconv -f WINDOWS-1252 -t UTF-8 data.csv > data-utf8.csv -
On Windows: enable UTF-8 mode
If your files are UTF-8 but Python defaults to cp1252, enable Python’s UTF-8 mode (
PYTHONUTF8=1orpython -X utf8). Since Python 3.15 (PEP 686), this mode is on by default.# PowerShell, current session $env:PYTHONUTF8 = "1" python script.py # or for a single run python -X utf8 script.py -
Last resort: replace unreadable bytes
errors="replace"replaces each invalid byte with the�character instead of crashing. It is handy for reading logs, but the affected characters are lost: do not use it on data you will save again. In pandas, the equivalent isencoding_errors="replace".with open("app.log", encoding="utf-8", errors="replace") as f: for line in f: print(line, end="")
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Always pass
encoding=toopen(),Path.read_text()andread_csv(). Pylint’sunspecified-encodingcheck, or the-X warn_default_encodingoption (Python 3.10+), flags the places you forgot. - Ask for exports in “CSV UTF-8” format and use UTF-8 as the single encoding across the project.
- Add a test that reads a sample file with accented characters, on Windows as well as Linux in CI.
Frequently asked questions
What is the difference between latin-1 and cp1252?
They match for most characters, but cp1252 uses the 0x80-0x9f range for €, ’, œ or …. latin-1 never fails, because it accepts every byte, but it can silently produce wrong characters.
Why does my script work on Mac but crash on Windows?
Without encoding=, Python uses the system default encoding: UTF-8 on macOS and Linux, often cp1252 on Windows before Python 3.15. Add encoding="utf-8" everywhere.
What does “byte 0xff in position 0: invalid start byte” mean?
The file starts with byte 0xff, which most often means a UTF-16 file. Open it with encoding="utf-16". If it is not text, read it in "rb" mode.
Useful tools for this error
More Python errors
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "'NoneType' object is not subscriptable" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "KeyError" in Python (dict, pandas, os.environ)
- Fix "RecursionError: maximum recursion depth exceeded" in Python
- Fix "attempted relative import with no known parent package" in Python