Python
UnicodeDecodeError
UTF-8
Error Handling
File I/O

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.

Practice algorithms

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.

python
with open("data.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line)

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.

python
with open("data.txt", "r", encoding="cp1252") as file:
    for line in file:
        print(line.rstrip())

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.

python
with open("data.txt", "rb") as file:
    for raw_line in file:
        print(raw_line[:20])

Then decode deliberately:

python
1with open("data.txt", "rb") as file:
2    for raw_line in file:
3        line = raw_line.decode("cp1252")
4        print(line.rstrip())

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.

python
with open("data.txt", "r", encoding="utf-8", errors="replace") as file:
    for line in file:
        print(line.rstrip())

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.

python
with open("image.png", "rb") as file:
    signature = file.read(8)
    print(signature)

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.

python
1def read_lines(path: str, encoding: str = "utf-8"):
2    with open(path, "r", encoding=encoding) as file:
3        for line in file:
4            yield line.rstrip("\n")

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 file loop 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

  • 'UnicodeDecodeError in 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.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
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.

Practice algorithms