Blog

Python UnicodeDecodeError Reading CSV: utf-8 codec Fix

Fix "utf-8 codec can't decode byte" when reading Excel CSVs in Python or pandas: Shift_JIS (cp932) versus UTF-8 with BOM, and how to tell them apart.

Diagram of bytes from one file splitting into two readers: one produces tidy rows, the other produces broken blocks
Contents

You receive a product list as a CSV from a supplier, try to total it up in Python, and the script stops on the very first line.

>>> open("items.csv", encoding="utf-8").read()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8f in position 0: invalid start byte

pandas read_csv() fails the same way. The file opens fine in Excel, so it is not corrupted. The cause is that the file is not encoded in UTF-8 but in Shift_JIS.

Then, after seeing the error, you add encoding="shift_jis", and sometimes a different error appears partway through the file. You ask the sender to re-save it as “CSV UTF-8” in Excel, the error disappears, and now row["商品コード"] raises KeyError. All of these come from the same problem, “a CSV from Excel and its character encoding”, but each symptom has a slightly different fix.

This article reproduces, one by one, the encoding errors you hit when reading and writing Excel and Windows CSV files in Python, using files built for the test. The environment is Python 3.13.18 and pandas 3.0.5 on Linux.

1. What the error means: a byte that cannot start a character in UTF-8

For the test I created a CSV in Shift_JIS (cp932, explained below), the same as Excel’s “CSV (Comma delimited)” format on Japanese Windows. It contains these four rows of product data.

商品コード,商品名,単価
A-001,ボールペン(黒),120
A-002,ノート①,180
A-003,髙島屋限定ファイル,350
A-004,クリップ~大,90

Reading the start of the file as bytes shows this.

>>> open("sjis.csv", "rb").read()[:12]
b'\x8f\xa4\x95i\x83R\x81[\x83h,\x8f'

\x8f\xa4 is 商 and \x95i is 品. Shift_JIS represents kanji and kana with two bytes, and the first byte falls in the range 0x81–0x9F or 0xE0–0xFC.

In UTF-8, on the other hand, bytes 0x80–0xBF only ever appear as the second or later byte of a multi-byte character. They never start a character, so a file beginning with 0x8f cannot be read as UTF-8, and you get invalid start byte (a byte that is not allowed at the start of a character).

The byte value in the error depends on the character where decoding failed. Hiragana and full-width letters start with 0x82 and katakana with 0x83, so the can't decode byte 0x82 and 0x83 errors you see all over the web have the same cause. position is the byte offset from the start of the file. If the first line contains only ASCII, the error appears where the first Japanese character is.

2. Excel has two kinds of CSV

When you choose CSV under “Save As” in Excel on Japanese Windows, at least these two formats are listed.

Save format Encoding Start of file encoding to use in Python
CSV (Comma delimited) Shift_JIS (Windows cp932) For Japanese text, usually 0x81–0x9F cp932
CSV UTF-8 (Comma delimited) UTF-8 with BOM EF BB BF utf-8-sig

“CSV (Comma delimited)” is written in the encoding of the Windows language setting, which is Shift_JIS on a Japanese system. Most CSV files exported by older systems and business software are also of this kind.

If you do not know which format you have, the first few bytes usually tell you.

>>> open("utf8bom.csv", "rb").read()[:12]
b'\xef\xbb\xbf\xe5\x95\x86\xe5\x93\x81\xe3\x82\xb3'

If the file starts with \xef\xbb\xbf, it is UTF-8 with a BOM (byte order mark). The \xe5\x95\x86 that follows is 商 in UTF-8. If there is no BOM and you see groups of three bytes starting in the 0xE0 range, such as \xe3 or \xe5, it is UTF-8 without a BOM. If you see pairs of bytes starting with \x82 or \x8f, it is Shift_JIS. On Linux or macOS, head -c 16 items.csv | xxd shows the same thing.

3. Use cp932, not shift_jis

Once you know it is Shift_JIS, you specify encoding and read it. With shift_jis, the test file stopped partway through.

>>> open("sjis.csv", encoding="shift_jis").read()
UnicodeDecodeError: 'shift_jis' codec can't decode byte 0x87 in position 64: illegal multibyte sequence

Byte 64 is the ① in ノート① (“notebook ①”). Python’s shift_jis is Shift_JIS as defined by the JIS standard, and it does not include circled numbers like ①, symbols like ㈱ or some traditional kanji forms like 髙. These are characters that NEC and IBM added, and they exist only in cp932 (Microsoft code page 932), the Windows version of Shift_JIS.

>>> for ch in "①髙㈱":
...     print(ch, ch.encode("cp932"))
① b'\x87@'
髙 b'\xee\xe0'
㈱ b'\x87\x8a'

All of them fail if you try to encode them with shift_jis. The “Shift_JIS” that Excel writes is really cp932, so in Python you specify cp932 (also known as windows-31j and ms932).

import csv

with open("sjis.csv", encoding="cp932", newline="") as f:
    for row in csv.DictReader(f):
        print(row["商品コード"], row["商品名"], row["単価"])
A-001 ボールペン(黒) 120
A-002 ノート① 180
A-003 髙島屋限定ファイル 350
A-004 クリップ~大 90

newline="" is the rule when using the csv module, so that line breaks inside cells are handled correctly (csv module documentation).

In pandas you pass the same value to the encoding argument.

import pandas as pd
df = pd.read_csv("sjis.csv", encoding="cp932")

The difference between shift_jis and cp932 is not only whether the extended characters exist. The bytes 0x81 0x60 are read by shift_jis as the wave dash 〜 (U+301C) and by cp932 as the full-width tilde ~ (U+FF5E). They look almost the same but are different characters, so strings read with shift_jis will not match other data. For CSV files from Excel, cp932 is the safer choice even when they contain no extended characters at all.

The same split exists in other languages: Python’s latin-1 and cp1252 differ in the 0x80–0x9F range (where cp1252 has €, curly quotes and dashes), and gb2312 covers fewer characters than gbk. Choose the Windows code page name when the file came from Excel.

4. Read UTF-8 with a BOM as utf-8-sig

A file saved as “CSV UTF-8” can be read with encoding="utf-8" without any error. But when you use column names with csv.DictReader, this happens.

>>> with open("utf8bom.csv", encoding="utf-8", newline="") as f:
...     r = csv.DictReader(f)
...     row = next(r)
...     print(r.fieldnames)
...     row["商品コード"]
['商品コード', '商品名', '単価']
KeyError: '商品コード'

utf-8 reads the BOM as an ordinary character (U+FEFF), so an invisible character is attached to the start of the first column name. Even print(row) shows “商品コード” on screen, which makes it hard to notice.

With encoding="utf-8-sig", the BOM at the start is removed before reading.

>>> with open("utf8bom.csv", encoding="utf-8-sig", newline="") as f:
...     print(next(csv.DictReader(f))["商品コード"])
A-001

utf-8-sig also reads files without a BOM as they are, so you can always use utf-8-sig when reading UTF-8 CSV files.

pandas read_csv(), in this environment, removed the BOM even with encoding="utf-8", and the column name became '商品コード'. That is why a script written with the csv module and one written with pandas can behave differently.

The BOM is not the only character that looks the same but does not match. If you suspect a zero-width space or a non-breaking space, paste the text into the Invisible Character Checker to see where it is. An example of a lookup failing in Excel for the same reason is covered in Why VLOOKUP returns #N/A and how to fix it.

5. ‘cp932’ codec can’t decode comes from the Windows default

There is also an error in the opposite direction: a script run on Windows reads a UTF-8 file and stops like this.

UnicodeDecodeError: 'cp932' codec can't decode byte 0x86 in position 2: illegal multibyte sequence

The code never says cp932, yet the error mentions 'cp932'. If you omit encoding in open(), Python up to 3.14 uses the encoding of the OS locale, and on Japanese Windows that is cp932 (open() documentation). On English Windows the same default is cp1252, on Russian Windows cp1251, and so on. The same script reads UTF-8 on Linux and macOS, so the problem tends to surface as “it works on my Mac but not on my colleague’s Windows PC”.

This error comes from reading e5 95 of UTF-8 商 (e5 95 86) as a two-byte cp932 character and getting stuck on the remaining 0x86. With bad luck, the whole file can be read without an error.

>>> "東京都".encode("utf-8").decode("cp932")
'譚ア莠ャ驛ス'

The string 東京都 (Tokyo) turns into garbage and flows on without any error, which is worse. With cp1252 the same mistake turns “café” into “café”.

In Python 3.15, released in October 2026, the default when encoding is omitted became UTF-8 on every OS (What’s New In Python 3.15, PEP 686). Windows also reads files as UTF-8, so this error becomes less likely. In exchange, Windows scripts that used to read Shift_JIS (or cp1252) CSV files without encoding will stop with the 'utf-8' codec can't decode error from the start of this article once you move to 3.15. You can restore the old behaviour with the environment variable PYTHONUTF8=0 or the -X utf8=0 option, but the surest way to get the same result on every Python version and OS is to always write encoding in both open() and read_csv(). When you really want the OS setting, you can say so explicitly with encoding="locale" (Python 3.10 and later).

6. Reading a file whose encoding you do not know

When the files you receive are sometimes Shift_JIS and sometimes UTF-8, a practical approach is to try UTF-8 first and fall back to cp932 if that fails.

def detect_encoding(path):
    data = open(path, "rb").read()
    for enc in ("utf-8-sig", "cp932"):
        try:
            data.decode(enc)
            return enc
        except UnicodeDecodeError:
            pass
    raise ValueError(f"{path}: cannot be read as UTF-8 or cp932")
sjis.csv     cp932
utf8bom.csv  utf-8-sig
utf8.csv     utf-8-sig

The order matters. As the previous section showed, a UTF-8 file can sometimes be “successfully” read as cp932. On the other hand, a Shift_JIS file containing Japanese almost never happens to satisfy UTF-8’s rules all the way through. So you try the stricter UTF-8 first. A short file with very little Japanese can still be misjudged, so if each supplier always uses the same encoding, storing that encoding in your settings is more reliable than guessing.

Be careful with single-byte code pages such as cp1252 as the fallback: almost every byte value decodes to some character, so the “try” rarely fails. Put such an encoding last, and only when you know which one the sender uses.

You will often see errors="ignore" or errors="replace" recommended to make the error go away, but adding them with the wrong encoding destroys the content.

>>> open("sjis.csv", encoding="utf-8", errors="replace").read()[:20]
'���i�R�[�h,���i��,�P'

Neither the column names nor the product names can be read any more, and no error is raised. Use errors only after reading with the correct encoding, when you want to tolerate a few broken bytes. In pandas the encoding_errors argument plays the same role.

If one folder mixes Shift_JIS and UTF-8, CRLF and LF, files with and without a BOM, and you want to make them all consistent, the guide to rescuing a folder of mixed-encoding files and the Charset Converter it uses work as they are.

7. UnicodeEncodeError when writing

Even when reading works, writing the result back in Shift_JIS can fail.

>>> "ハイフン—ダッシュ".encode("cp932")
UnicodeEncodeError: 'cp932' codec can't encode character '—' in position 4: illegal multibyte sequence
>>> "寿司🍣".encode("cp932")
UnicodeEncodeError: 'cp932' codec can't encode character '\U0001f363' in position 2: illegal multibyte sequence

cp932 covers JIS kanji, kana and symbols plus the Windows extensions, which is only a small part of Unicode. The em dash — (U+2014) and emoji that turn up in text collected from the web have no counterpart in cp932. The same is true of cp1252 and the other single-byte code pages, which cannot hold most characters outside their own script.

If the output is a CSV to be opened in Excel, the simple answer is not to insist on Shift_JIS and to write UTF-8 with a BOM. Excel sees the BOM and recognises the file as UTF-8, so it does not garble the text even when opened by double-clicking.

with open("out.csv", "w", encoding="utf-8-sig", newline="") as f:
    csv.writer(f).writerows(rows)

df.to_csv("out.csv", index=False, encoding="utf-8-sig")

If you write plain utf-8 without a BOM, Excel may read the file in the local code page when it is opened by double-clicking, and the text comes out garbled.

If the system you import into accepts only Shift_JIS, look for characters that cannot be converted to cp932 before writing, and decide whether to replace them.

def find_non_cp932(text):
    for i, ch in enumerate(text):
        try:
            ch.encode("cp932")
        except UnicodeEncodeError:
            yield i, ch, f"U+{ord(ch):04X}"

print(list(find_non_cp932("ハイフン—ダッシュ 寿司🍣")))
# [(4, '—', 'U+2014'), (12, '🍣', 'U+1F363')]

Once you know which character in which row is the problem, you can decide, for example, to replace — with ― (U+2015, which cp932 has). Turning everything into ? with errors="replace" lets product names and addresses be imported with pieces missing.

8. Looking up the cause from the error message

Here is everything above in a form you can look up by error message.

Symptom Cause Fix
'utf-8' codec can't decode byte 0x82 (0x83, 0x8f, etc.): invalid start byte A Shift_JIS file was read as UTF-8. The UTF-8 default in Python 3.15 can also cause it encoding="cp932" (or your locale’s code page)
'shift_jis' codec can't decode byte 0x87 (0xED, 0xEE, 0xFA, etc.) The file contains Windows extended characters such as ①, ㈱ or 髙 Change shift_jis to cp932
The column name becomes '商品コード' and you get KeyError UTF-8 with a BOM was read as utf-8 encoding="utf-8-sig"
'cp932' codec can't decode, or garbage like 譚ア莠ャ A UTF-8 file was read on Windows without encoding Write encoding="utf-8-sig" explicitly
'cp932' codec can't encode character Characters not in cp932 (—, emoji, etc.) were written as Shift_JIS For Excel, write utf-8-sig. If Shift_JIS is required, find those characters and replace them

Encoding problems happen when the environment that hands over the file differs from the one that receives it. A shell script written on Windows failing on Linux with $'\r': command not found is the same pattern, caused there by different line endings (Fixing $’\r’: command not found). In every case, using the byte value in the error message as a clue and looking at the file as bytes once makes the cause easier to find. Reading bytes as characters is also covered in Reading the ASCII code table: telling CR LF (0D 0A) from the digit 0.

Try it yourself

Code to reproduce the results in this article (Python 3, standard library only)

Save the following code as csv_encoding_check.py and run python3 csv_encoding_check.py in an empty folder. It creates three CSV files, in Shift_JIS (cp932), UTF-8 with a BOM and UTF-8 without a BOM, and prints the errors and results from the article in order.

import csv

rows = ("商品コード,商品名,単価\n"
        "A-001,ボールペン(黒),120\n"
        "A-002,ノート①,180\n"
        "A-003,髙島屋限定ファイル,350\n"
        "A-004,クリップ~大,90\n")
crlf = rows.replace("\n", "\r\n")
open("sjis.csv", "wb").write(crlf.encode("cp932"))
open("utf8bom.csv", "wb").write(crlf.encode("utf-8-sig"))
open("utf8.csv", "wb").write(rows.encode("utf-8"))

def show(label, func):
    try:
        print(label, "→", func())
    except Exception as e:
        print(label, "→", type(e).__name__, e)

show("sjis as utf-8", lambda: open("sjis.csv", encoding="utf-8").read())
show("sjis as shift_jis", lambda: open("sjis.csv", encoding="shift_jis").read())
show("sjis as cp932", lambda: open("sjis.csv", encoding="cp932").read().splitlines()[2])
show("head bytes", lambda: open("utf8bom.csv", "rb").read()[:3])

with open("utf8bom.csv", encoding="utf-8", newline="") as f:
    print(csv.DictReader(f).fieldnames)
with open("utf8bom.csv", encoding="utf-8-sig", newline="") as f:
    print(csv.DictReader(f).fieldnames)

show("utf8 as cp932", lambda: open("utf8.csv", encoding="cp932").read())
show("東京都 utf8→cp932", lambda: "東京都".encode("utf-8").decode("cp932"))
show("— to cp932", lambda: "—".encode("cp932"))

If pandas is installed, these two lines show how it handles the BOM.

import pandas as pd
print(pd.read_csv("utf8bom.csv", encoding="utf-8").columns.tolist())