LoginSignup
13
19

More than 5 years have passed since last update.

Python UTF-8のCSVファイル読み込み (UnicodeDecodeError対応)

Last updated at Posted at 2018-04-09

PythonでCSV(UTF-8)を読み込みするとエラーが発生したときの対応。
encodingでUTF-8を指定した。Python3 公式CODEC一覧

UTF-8は指定なしで読み込めるらしいけど、環境によるのかな。
今度まじめに調べたら記事更新しよう。


shiracamusさんからコメントで教えて頂きました。
デフォルトはOS標準になるとのことです。


環境

  • Windows10
  • Python3.6.0

発生したエラー

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

正常に動作したコード

import csv

with open('data.csv', encoding="utf_8") as file:
    reader = csv.reader(file)

    for row in reader:
        print(row)

※"utf_8" -> "utf-8"でも動く
※引数でファイルを開くモードはデフォルトがmode='r'(読み込み用)なので読み込み用途なら省略できます。

13
19
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
19