csvファイルを読み込む

文字コードがshift-jsだと、
[vagrant@localhost python]$ python3 app.py
Traceback (most recent call last):
File “app.py”, line 4, in
csv = codecs.open(filename, “r”, “shift_jis”).read()
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/codecs.py”, line 698, in read
return self.reader.read(size)
UnicodeDecodeError: ‘shift_jis’ codec can’t decode byte 0xef in position 0: illegal multibyte sequence

utf-8にします。

import codecs

filename = "list-sjis.csv"
csv = codecs.open(filename, "r", "utf-8").read()

data = []
rows = csv.split("\r\n")
for row in rows:
	if row == "": continue
	cells = row.split(",")
	data.append(cells)

for c in data:
	print(c[1], c[2])

[vagrant@localhost python]$ python3 app.py
商品名 値段
石鹸 300
手袋 150
マスク 230

import csv, codecs

filename = "list-sjis.csv"
fp = codecs.open(filename, "r", "utf-8")

reader = csv.reader(fp, delimiter=",", quotechar='"')
for cells in reader:
	print(cells[1], cells[2])

このようにも書けますね。