导入CSV文件时Python 3中的UnicodeDecodeError

时间:2012-10-05 18:49:54

标签: python unicode csv python-3.x non-ascii-characters

我正在尝试使用以下代码导入CSV:

    import csv
    import sys

    def load_csv(filename):
        # Open file for reading
        file = open(filename, 'r')

        # Read in file
        return csv.reader(file, delimiter=',', quotechar='\n')

    def main(argv):
        csv_file = load_csv("myfile.csv")

        for item in csv_file:
            print(item)

    if __name__ == "__main__":
        main(sys.argv[1:])

以下是我的csv文件示例:

    foo,bar,test,1,2
    this,wont,work,because,α

错误:

    Traceback (most recent call last):
      File "test.py", line 22, in <module>
        main(sys.argv[1:])
      File "test.py", line 18, in main
        for item in csv_file:
      File "/usr/lib/python3.2/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 40: ordinal not in range(128)

显然,它正在击中CSV末尾的角色并抛出该错误,但我不知道如何解决这个问题。有什么帮助吗?

这是:

    Python 3.2.3 (default, Apr 23 2012, 23:35:30)
    [GCC 4.7.0 20120414 (prerelease)] on linux2

3 个答案:

答案 0 :(得分:14)

看来你的问题归结为:

print("α")

您可以通过指定PYTHONIOENCODING

来解决此问题
$ PYTHONIOENCODING=utf-8 python3 test.py > output.txt

注意:

$ python3 test.py 

应该按照您的终端配置支持它,test.py

import csv

with open('myfile.csv', newline='', encoding='utf-8') as file:
    for row in csv.reader(file):
        print(row)

如果open()上面没有encoding参数,那么UnicodeDecodeError LC_ALL=C将获得LC_ALL=C

同样使用UnicodeEncodeError,即使没有重定向,您也会获得PYTHONIOENCODING,即在这种情况下需要{{1}}。

答案 1 :(得分:13)

python docs,您必须设置文件的编码。以下是该网站的示例:

import csv

 with open('some.csv', newline='', encoding='utf-8') as f:
   reader = csv.reader(f)
   for row in reader:
     print(row)

编辑:您的问题似乎与打印有关。尝试使用漂亮的打印机:

import csv
import pprint

with open('some.csv', newline='', encoding='utf-8') as f:
  reader = csv.reader(f)
  for row in reader:
    pprint.pprint(row)

答案 2 :(得分:0)

另一种选择是通过传递错误处理程序来掩盖错误:

with open('some.csv', newline='', errors='replace') as f:
   reader = csv.reader(f)
   for row in reader:
    print(row)

它将用“缺少字符”替换文件中所有无法解码的字节。