我正在运行一个处理30,000个类似文件的程序 . 随机数量正在停止并产生此错误......
File "C:\Importer\src\dfman\importer.py", line 26, in import_chr
data = pd.read_csv(filepath, names=fields)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 400, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 205, in _read
return parser.read()
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 608, in read
ret = self._engine.read(nrows)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 1028, in read
data = self._reader.read(nrows)
File "parser.pyx", line 706, in pandas.parser.TextReader.read (pandas\parser.c:6745)
File "parser.pyx", line 728, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:6964)
File "parser.pyx", line 804, in pandas.parser.TextReader._read_rows (pandas\parser.c:7780)
File "parser.pyx", line 890, in pandas.parser.TextReader._convert_column_data (pandas\parser.c:8793)
File "parser.pyx", line 950, in pandas.parser.TextReader._convert_tokens (pandas\parser.c:9484)
File "parser.pyx", line 1026, in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:10642)
File "parser.pyx", line 1046, in pandas.parser.TextReader._string_convert (pandas\parser.c:10853)
File "parser.pyx", line 1278, in pandas.parser._string_box_utf8 (pandas\parser.c:15657)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xda in position 6: invalid continuation byte
这些文件的来源/创建都来自同一个地方 . 什么是纠正此问题以进行导入的最佳方法?
5 回答
read_csv
采用encoding
选项来处理不同格式的文件 . 我主要使用read_csv('file', encoding = "ISO-8859-1")
,或者encoding = "utf-8"
用于阅读,一般utf-8
用于to_csv
.您也可以使用alias
'latin1'
而不是'ISO-8859-1'
.请参阅relevant Pandas documentation,python docs examples on csv files以及SO上的大量相关问题 .
Simplest of all Solutions:
在Sublime文本编辑器中打开csv文件 .
以utf-8格式保存文件 .
然后,您可以照常阅读您的文件:
EDIT 1:
如果有许多文件,则可以跳过sublime步骤 .
只需阅读文件即可
和其他不同的编码类型是:
Pandas允许指定编码,但不允许忽略错误而不是自动替换有问题的字节 . 所以没有一种尺寸适合所有方法,但根据实际使用情况不同的方式 .
Latin1
编码,因为它接受任何可能的字节作为输入(并将其转换为相同代码的unicode字符):open
函数有(假设是Python3),而read_csv
接受像object这样的文件 . 这里使用的典型错误参数是'ignore'
,它只是抑制有问题的字节或(恕我直言更好)'backslashreplace'
,它用Python的反斜杠转义序列替换有问题的字节:挣扎了一段时间,并认为我会发布这个问题,因为这是第一个搜索结果 . 将encoding ='iso-8859-1“标签添加到pandas read_csv不起作用,也没有任何其他编码,继续给出UnicodeDecodeError .
如果要将文件句柄传递给pd.read_csv(),则需要在文件上打开encoding =属性,而不是在read_csv中 . 事后看来很明显,但要追踪到一个微妙的错误 .
执行此代码后,您将找到'filename.csv'的编码,然后按如下方式执行代码
你去吧