非asciiのCSVを扱う人はPython 3000を使う方がいいと思う

Python 2.x系では、codecs.open()で開いたファイルをそのままcsv.reader()に渡すと、エラーが出てしまいます。ところがこれ、Python 3.xだと問題なくちゃんと扱ってくれるんです。

試しにこんなコードを書いてみました。

import codecs
import csv

with codecs.open('./data.csv', 'r', 'shift_jis') as f:
    reader = csv.reader(f)
    for row in reader:
        print('{0[0]}: {0[1]}'.format(row))

こういうCSVを用意してやります。名前はdata.csv。Shift JISで保存しました。

"商品1",20
"商品2",15
"商品3",30

これをPython 2.xで実行するとエラーが出ます*1

$ python2.6 test.py 
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    for row in reader:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)

しかしこれがPython 3.xだと大丈夫なんですね。

$ python test.py 
商品1: 20
商品2: 15
商品3: 30

これだけのことですが、非asciiのデータを扱う人はPython 3000を使うに充分な理由になると思っています。実施、私、CGI書く時はPython 2.6を使ってますが、普段の作業はPython 3000に完全に移行しています。

*1:うまく処理する方法もあって、以前はそれで非asciiのCSVを扱ってたのですが、忘れました。今度探しておきます。