UnicodeDecodeError in Python — What It Means and How to Fix It
What Python's UnicodeDecodeError exception means and how to resolve it.
Published October 28, 2026
UnicodeDecodeError is raised when bytes cannot be decoded using the chosen encoding, typically reading a file that is not UTF-8.
What it means and why it happens
Typical causes: files saved as latin-1, UTF-16 or Windows-1252, binary files opened as text or wrong default encodings.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0
Practical examples
Code that triggers it
open('data.txt').read()The fix
open('data.txt', encoding='utf-8', errors='replace').read()
# or the correct encoding
open('data.txt', encoding='latin-1').read()Detect encoding
file -i data.txt
pip install chardet
chardetect data.txtCommon mistakes
- Relying on the platform default encoding.
- Ignoring errors silently with errors='ignore'.
- Opening binary files in text mode.
Key takeaways
- UnicodeDecodeError: UnicodeDecodeError is raised when bytes cannot be decoded using the chosen encoding, typically reading a file that is not UTF-8.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
How do I read binary?
Open with 'rb' and decode explicitly.
How do I find which line caused UnicodeDecodeError?
The error message and stack trace show the file and line; start there and work backwards.