for line in... results in UnicodeDecodeError 'utf-8' codec can't decode byte
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
If for line in file raises UnicodeDecodeError, the loop is not usually the real problem. The underlying issue is that Python is reading bytes and trying to decode them as UTF-8 text even though the file's actual bytes do not match UTF-8.
Why the Error Happens
When you open a file in text mode, Python decodes bytes into str values. If you asked for UTF-8, or your environment default is UTF-8, every byte sequence must be valid under that encoding.
If the file is really cp1252, latin-1, mixed text, or binary data, decoding fails before the loop can continue.
Use the Correct Encoding When You Know It
The best solution is to open the file using its real encoding.
This is the right fix when the source format is known. Many Windows-generated text files are cp1252, and some legacy exports are latin-1. If you control the whole pipeline, standardizing on UTF-8 is even better than patching readers one by one.
Read Bytes First When the Encoding Is Unclear
If you do not know the encoding, start in binary mode and inspect the raw bytes. That separates file reading from text decoding.
Then decode deliberately:
This approach is useful when some files are valid UTF-8 and others are not. It lets you build a decoding policy instead of guessing.
Use Error Strategies Only When Loss Is Acceptable
Python supports decoding modes such as replace and ignore.
Those settings keep the program running, but they do not preserve the original text accurately. ignore silently drops bytes, and replace inserts replacement characters. That can be acceptable for rough log viewing, but it is a poor default for data pipelines where exact text matters.
Some Inputs Are Not Text Files
Another common cause is treating a binary file as if it were text. An image, compressed file, or corrupted export may contain byte sequences that no text decoder should be expected to handle.
If the file is binary, the fix is not to search for a better text encoding. The fix is to stop opening it as text.
Make Encoding an Explicit API Choice
If your code reads external files frequently, make the encoding visible rather than relying on platform defaults.
This makes the behavior more portable and easier to debug. Hidden defaults often work on one machine and fail on another.
Common Pitfalls
- Blaming the
for line in fileloop when the real problem is decoding. - Assuming every text file is UTF-8.
- Using
errors="ignore"and silently corrupting data. - Reading unknown inputs as text instead of starting in binary mode.
- Treating a binary file as if it were merely a text file with the wrong encoding.
Summary
- '
UnicodeDecodeErrorin a line-reading loop usually means an encoding mismatch.' - The best fix is to open the file with the correct encoding.
- If the encoding is unknown, read bytes first and decode deliberately.
- Use replacement or ignore strategies only when data loss is acceptable.
- Some files are binary, and no text decoder will make them valid text.
Related reading
- Force Anaconda to install tensorflow 1.14
- Forecast future values with LSTM in Python
- Format / Suppress Scientific Notation from Pandas Aggregation Results
- Format numbers in django templates
- Forbidden to access Kubernetes API Server
- Forms not responding to KeyDown events
- Format timedelta to string
- Formatting floats without trailing zeros
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.