【发布时间】:2019-01-31 08:18:12
【问题描述】:
我正在尝试使用以下 python 脚本将所有 CSV 元素转换为 python 对象,但并非 CSV 文件中的所有字符都是 UTF-8,我必须将所有这些字符转换为可读格式,即 UTF-8。我怎样才能做到这一点?
我尝试使用简单的文本编辑器将 csv 文件转换为 UTF-8,就像 How to convert csv files encoding to utf-8 一样,但无能为力。
我正在使用以下 python 文件:
import csv
filename = "file.csv"
rows = []
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
rows.append(row)
print("Total no. of rows: %d"%(csvreader.line_num))
print('\nFirst 5 rows are:\n')
for row in rows[:5]:
for col in row:
print("%10s"%col),
print('\n')
Python 产生以下错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 4942: invalid start byte
【问题讨论】:
-
你可以试试:
open(filename, 'r',encoding='utf-16')吗? -
错误提示文件不是utf8编码的。您是否知道实际的编码,或者您是否需要一种不会中断但会给出奇怪字符的 catch all 方式?
-
@ArtemTrunov UnicodeError: UTF-16 流不以 BOM 开头
-
@SergeBallesta 我不知道是哪种编码。