17

我正在尝试使用以下代码导入 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
4

3 回答 3

21

看来您的问题归结为:

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你也会得到,即,在这种情况下是必要的(在PEP 538:在 Python 3.7+ 中实现的 Legacy C Locale Coercion 之前)。UnicodeEncodeErrorPYTHONIOENCODING

于 2012-10-05T19:37:09.377 回答
13

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

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)
于 2012-10-05T18:55:15.467 回答
5

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

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

它将用“缺失字符”替换文件中任何不可解码的字节。

于 2019-12-30T20:40:19.700 回答