【问题标题】:I get python frameworks error while reading a csv file, when I try a different easier file it works fine读取 csv 文件时出现 python 框架错误,当我尝试使用其他更简单的文件时,它工作正常
【发布时间】:2016-12-23 06:57:19
【问题描述】:
import csv



exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
       print('Row #' + str(exampleReader.line_num) + ' ' + str(row))



Traceback (most recent call last):
      File "/Users/jossan113/Documents/Python II/test.py", line 7, in <module>
        for row in exampleReader:
      File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 4627: ordinal not in range(128)

有人知道我为什么会收到此错误吗?我从互联网上尝试了一个非常简单的 cvs 文件,它工作得很好,但是当我尝试更大的文件时它没有

【问题讨论】:

    标签: python file csv import frameworks


    【解决方案1】:

    该文件包含 unicode 字符,这在旧版本的 python 中处理起来很痛苦,因为您使用的是 3.5 尝试以 utf-8 格式打开文件并查看问题是否消失:

    exampleFile = open('example.csv', encoding="utf-8")
    

    来自文档:

    由于 open() 用于打开 CSV 文件进行读取,默认情况下该文件将使用系统默认编码解码为 un​​icode(参见 locale.getpreferredencoding())。要使用不同的编码解码文件,请使用 open 的 encoding 参数:

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

    csv modeule docs

    【讨论】:

    • 我明白了:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 4627: invalid start byte 我可以告诉我的教授,也许他可以修复它,这样它就可以工作了大家,我不认为这是故意的
    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2018-08-17
    • 2020-07-20
    相关资源
    最近更新 更多