【问题标题】:How to read csv file with python 3如何使用 python 3 读取 csv 文件
【发布时间】:2020-06-11 11:15:12
【问题描述】:

我想用 python3.7 读取一个 csv 文件,但是我的代码给了我以下错误:

Traceback (most recent call last):
  File "python_to_csv.py", line 6, in <module>
    for row in csv_data:
  File "/usr/lib/python3.7/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 24: invalid start byte

这是我的代码:

import csv
csv_data =  csv.reader(open('videos.export-full.csv', 'r'), delimiter=';') 
for row in csv_data:
    print (row)

我该如何解决这个问题并将记录插入数据库? 您可以从http://li2146-47.members.linode.com/videos.export-full.csv 下载 csv 文件的副本以自行测试。

【问题讨论】:

  • 这能回答你的问题吗? Python 3: CSV files and Unicode Error
  • 不,它没有回答我的问题
  • open 默认会使用系统默认编码解码成 unicode,你应该通过open('some.csv', newline='', encoding='utf-8')指定编码

标签: python encoding python-3.7


【解决方案1】:

'\xb3'³ 的 unicode 代码(SUPERSCRIPT 3)。该错误提示该文件不是 UTF-8 编码的,但可能是 ISO-8859-1(或 Latin1)编码的。所以你应该使用:

csv_data =  csv.reader(open('videos.export-full.csv', 'r', encoding='Latin1'), delimiter=';')

您应该控制数据,因为Latin1 能够转换任何字节,无论编码如何,但如果编码不是 ISO-8859-1,您将无法获得预期的字符。

【讨论】:

  • 上面写着Traceback (most recent call last): File "python_to_csv.py", line 6, in &lt;module&gt; for row in csv_data: _csv.Error: line contains NULL byte
  • @Jsdoee 你也尝试过 ISO 编码吗?
  • 查找错误:未知编码:ISO
  • @Jsdoee:如果你得到一个空字节,数据可能是 UTF16。你应该试试 utf_16_le 或 utf_16_be。
  • 第一句话是错误的,具有误导性。没有 unicode 的二进制表示(对于答案的其余部分也没有用)。
【解决方案2】:

更改以下内容

import csv

csv_data =  csv.reader('videos.export-full.csv')

for row in csv_data:

print (row)

它应该可以工作

【讨论】:

  • 上面写着Traceback (most recent call last): File "python_to_csv.py", line 14, in &lt;module&gt; for row in csv_data: File "/usr/lib/python3.7/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 24: invalid start byte
  • 重试究竟是什么,我不明白
  • @Jsdoee:我已经编辑了代码并输出了一个列表。
猜你喜欢
  • 2016-04-06
  • 2010-12-08
  • 1970-01-01
  • 2011-08-12
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多