【问题标题】:UnicodeDecodeError in python-3.4python-3.4 中的 UnicodeDecodeError
【发布时间】:2017-01-06 05:04:36
【问题描述】:

我在 Jupyter Notebook 中使用 Python (3.4),默认情况下应该已经使用 utf-8。但是从 csv 文件中读取一些数据时出现以下错误。知道如何解决这个问题吗?谢谢!

从 csv 文件中读取的代码:

with open('my_data.csv') as csvfile:
    line = csv.reader(csvfile)

    for row in line:
        print (row)

错误:

Last executed 2017-01-06 04:58:59 in 85ms
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-19-09c617346fbb> in <module>()
     14     line = csv.reader(csvfile)
     15 
---> 16     for row in line:
     17         print (row)

/usr/lib/python3.4/encodings/ascii.py in decode(self, input, final)
     24 class IncrementalDecoder(codecs.IncrementalDecoder):
     25     def decode(self, input, final=False):
---> 26         return codecs.ascii_decode(input, self.errors)[0]
     27 
     28 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 2588: ordinal not in range(128)

【问题讨论】:

    标签: python-3.x unicode encoding jupyter-notebook


    【解决方案1】:

    打开文件时指定编码。同样根据csv module documentation 使用newline='' 选项作为要包装的文件:

    with open('my_data.csv',encoding='utf8',newline='') as csvfile:
        line = csv.reader(csvfile)
    

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 1970-01-01
      • 2017-05-03
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2018-02-21
      相关资源
      最近更新 更多