[英]How to read csv file with python 3
I want to read a csv file with python3.7, but my code gives me the following error:我想用 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
Here is my code:这是我的代码:
import csv
csv_data = csv.reader(open('videos.export-full.csv', 'r'), delimiter=';')
for row in csv_data:
print (row)
How can I solve this issue and insert the records in the database?我该如何解决这个问题并将记录插入数据库? You can download a copy of the csv file from http://li2146-47.members.linode.com/videos.export-full.csv to test it yourself.
大家可以到http://li2146-47.members.linode.com/videos.export-full.csv下载一份csv文件自己测试。
Change the following更改以下内容
import csv
csv_data = csv.reader('videos.export-full.csv')
for row in csv_data:
print (row)
It should work它应该工作
'\xb3'
is the unicode code for ³
(SUPERSCRIPT THREE). '\xb3'
是³
(SUPERSCRIPT THREE)的 unicode 代码。 The error is a hint that the file is not UTF-8 encoded but is probably ISO-8859-1 (or Latin1) encoded.该错误提示该文件不是 UTF-8 编码的,但可能是 ISO-8859-1(或 Latin1)编码的。 So you should use:
所以你应该使用:
csv_data = csv.reader(open('videos.export-full.csv', 'r', encoding='Latin1'), delimiter=';')
You should control the data because Latin1
is able to convert any byte whatever the encoding, but if encoding is not ISO-8859-1, you do not get the expected characters.您应该控制数据,因为
Latin1
能够转换任何编码的任何字节,但如果编码不是 ISO-8859-1,您将无法获得预期的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.