Python3 CSV阅读器Unicode编码

2024-05-13 19:44:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用utf8编码的巨大csv文件,但是有些列的编码与主文件编码不同。它看起来像:

输入.txtUTF-8编码中的

a,b,c
d,"e?",f
g,h,"kü"

相同输入.txt在win-1252中

^{pr2}$

代码:

import csv

file = open("input.txt",encoding="...")
c = csv.reader(file, delimiter=';', quotechar='"')

for itm in c:
    print(itm)

而standart python3csv阅读器会在这些行上产生编码错误,我不能忽略这一行的阅读,我只需要总是编码良好的“someOther”列。在

是否可以使用standart csv reader以某种“字节模式”分割csv数据,然后将每个数组元素转换为普通的python unicode字符串,还是应该实现自己的csv读取器?在

回溯:

Traceback (most recent call last):
  File "C:\Development\t.py", line 7, in <module>
    for itm in c:
  File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 11: invalid start byte

Tags: 文件csvinpyselftxt编码for
1条回答
网友
1楼 · 发布于 2024-05-13 19:44:34

你有多确定你的文件是UTF8编码的?在

对于您发布的小示例,UTF8解码在ü上失败,这是“带分音符的拉丁文小写字母U”。当编码为ISO-8859-1时,ü'\xfc'。另外两种可能性是CSV文件是UTF-16编码的(UTF-16 little-endian在Windows上很常见),甚至是Windows-1252。在

如果您的CSV文件是用ISO-8859-X编码系列之一编码的;则ISO 8859-1/3/4/9/10/14/15/16中的任何一个都将ü编码为0xfc。在

若要解决此问题,请使用正确的编码并按如下方式打开文件:

file = open("input.txt", encoding="iso-8859-1")

或者,对于Windows 1252:

^{pr2}$

或者,对于UTF-16:

file = open("input.txt", encoding="utf-16")    # or utf-16-le or utf-16-be as required

相关问题 更多 >