[英]How to read csv file with python 3
我想用 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文件自己測試。
更改以下內容
import csv
csv_data = csv.reader('videos.export-full.csv')
for row in csv_data:
print (row)
它應該工作
'\xb3'
是³
(SUPERSCRIPT THREE)的 unicode 代碼。 該錯誤提示該文件不是 UTF-8 編碼的,但可能是 ISO-8859-1(或 Latin1)編碼的。 所以你應該使用:
csv_data = csv.reader(open('videos.export-full.csv', 'r', encoding='Latin1'), delimiter=';')
您應該控制數據,因為Latin1
能夠轉換任何編碼的任何字節,但如果編碼不是 ISO-8859-1,您將無法獲得預期的字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.