GVKun编程网logo

使用 Python 在 Pandas 中读取 CSV 文件时出现 UnicodeDecodeError(pandas读取csv文件出错)

9

如果您想了解使用Python在Pandas中读取CSV文件时出现UnicodeDecodeError的相关知识,那么本文是一篇不可错过的文章,我们将对pandas读取csv文件出错进行全面详尽的解释,

如果您想了解使用 Python 在 Pandas 中读取 CSV 文件时出现 UnicodeDecodeError的相关知识,那么本文是一篇不可错过的文章,我们将对pandas读取csv文件出错进行全面详尽的解释,并且为您提供关于Anaconda中启动Python时的错误:UnicodeDecodeError: ''gbk'' codec can''t decode byte 0xaf in posit...、Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte、mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...、Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?的有价值的信息。

本文目录一览:

使用 Python 在 Pandas 中读取 CSV 文件时出现 UnicodeDecodeError(pandas读取csv文件出错)

使用 Python 在 Pandas 中读取 CSV 文件时出现 UnicodeDecodeError(pandas读取csv文件出错)

我正在运行一个正在处理 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

这些文件的来源/创建都来自同一个地方。纠正此问题以继续导入的最佳方法是什么?

答案1

小编典典

read_csv可以encoding选择处理不同格式的文件。我主要使用read_csv(''file'', encoding ="ISO-8859-1"), 或者encoding = "utf-8"用于阅读,通常utf-8用于to_csv.

您还可以使用多个alias选项之一,例如''latin''or
''cp1252''(Windows),而不是''ISO-8859-1''(请参阅python
文档,也可以使用您可能遇到的许多其他编码)。

请参阅相关的 Pandas 文档、 csv 文件上的 python
文档示例,以及关于 SO
的大量相关问题。一个好的背景资源是每个开发人员都应该知道的关于 unicode
和字符集的知识。

要检测编码(假设文件包含非 ascii
字符),您可以使用enca(参见手册页)或file-i(linux)或file -I(osx)(参见手册页)。

Anaconda中启动Python时的错误:UnicodeDecodeError: ''gbk'' codec can''t decode byte 0xaf in posit...

Anaconda中启动Python时的错误:UnicodeDecodeError: ''gbk'' codec can''t decode byte 0xaf in posit...

今天,在Anaconda prompt启动python遇到了如下错误:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xaf in position 553: illegal multibyte sequence

 

看了看出错跟踪,查看了如下位置:

C:\ProgramData\Anaconda3\lib\site.py", line 439

如下图所示,发现是读取history指定的路径的文件出错,于是就通过python看了看

os.path.join(os.path.expanduser(’~’),’.python_history’)的计算所得路径为(注意:???表示电脑用户名,每个人设置不同,请参照自己实际情况):

C:\Users\???\.python_history

 

打开上述文件,发现是上次关闭之前的python命令记录等,里面有汉字注释,Python的命令窗口的本身编码为来自系统设置的GBK引起的文件存成了gbk编码。如果历史记录对你来说没什么用处,最简单的办法就是删除掉.python_history文件,就可以了。我自己是通过如下方式解决的,操作系统是Windows 10 1803 (April 2018 Update) 以上版本的话,可以"Region" - “Administrative” - “Change system locale” - "Region Settings"中选中 "Beta: Use Unicode UTF-8 for worldwide language support"选项。

 

Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte

Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte

错误信息如下:
在Eclipse上面运行python脚本时报错
网上报这个错误的原因有很多,包括:

  1. 脚本本身不是使用UTF-8编码的,需要转成utf-8编码
  2. 脚本的头部需要声明为:utf-8 编码 脚本头部需要使用utf8编码
  3. 工程路径中包含中文字符也会报这个错误,因为python会读取windows中工程路径,而windows中的编码一般都是亲生的gbk类编码不太容易修改,所以这种情况下需要将你的工程移到没有中文字符的目录下,然后在重新导入.

mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...

mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...

  在储存用户密码时,我使用了 hmac 算法对用户密码加密,加密出来的 hash 值是一个二进制字节串,我把这个字节串存到 mysql 的 password 字段,password 字段的数据类型是 varbinary。

  在验证用户密码时,我把用户输入的密码经过同样的 hmac 算法得到 hash 值,然后从数据库 password 字段的字节串取出来,比较两个字节串是否相等。

  在开发环境中,这样做没有任何问题,但是当我把代码部署到 centos7 的服务器上时,存 password 字节串没有问题,却在取 password 字段的字节串时出现了 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb0 in position 0 的错误。

  其实仔细看一下,这个问题的根源在于 mysqlconnector 试图将二进制字节解码为 unicode,也就是字符串,但其实我们是不需要这样做的,我们只需要将这个二进制字节完完整整地取出来。

  因为我的生产和开发环境的 mysql 版本不同,因此开发环境中,不需要任何设置 mysqlconnector 就自动不会对二进制字节进行解码。我们现在要做的就很简单,阻止 mysqlconnector 解码二进制字节。

  查看 mysqlconnector 的源码,在 cursor_cext.py 找到 CMySQLCursor 类,这个类的实例就是我们用的 cursor,但是这个类的 fetchone、fetchall、fetchmany 等函数都不接受编码相关的参数,因此可能不能通过设置 cursor 来解决,于是我又在官网上找到了 connect(连接数据库的函数)的配置参数说明

  找到 use_unicode 一项,这个参数控制 mysqlconnector 在取数据的时候会不会将二进制字节解码为字符串,它的默认值是 True。用法如下

mysql.connector.connect(**config,use_unicode=False)

  这样取出来的数据类型为 <class ''bytes''>,这个错误也不会出现了

Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?

Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?

我有一个文本文件,发布者(美国证券交易委员会)断言该文本文件以UTF-8编码(https://www.sec.gov/files/aqfs.pdf,第4节)。我正在使用以下代码处理代码行:

def tags(filename):    """Yield Tag instances from tag.txt."""    with codecs.open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f:        fields = f.readline().strip().split(''\t'')        for line in f.readlines():            yield process_tag_record(fields, line)

我收到以下错误:

Traceback (most recent call last):  File "/home/randm/Projects/finance/secxbrl.py", line 151, in <module>    main()  File "/home/randm/Projects/finance/secxbrl.py", line 143, in main    all_tags = list(tags("tag.txt"))  File "/home/randm/Projects/finance/secxbrl.py", line 109, in tags    content = f.read()  File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 698, in read    return self.reader.read(size)  File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 501, in read    newchars, decodedbytes = self.decode(data, self.errors)UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xad in position 3583587: invalid start byte

鉴于我可能无法回到SEC并告诉他们它们包含的文件似乎未采用UTF-8编码,我应该如何调试和捕获此错误?

我尝试了什么

我对文件进行了十六进制转储,发现有问题的文本是文本``非现金投资的补充披露’‘。如果我将有问题的字节解码为十六进制代码点(即“ U +
00AD”),则在上下文中是有意义的,因为它是软连字符。但是以下似乎无效:

Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linuxType "help", "copyright", "credits" or "license" for more information.>>> b"\x41".decode("utf-8")''A''>>> b"\xad".decode("utf-8")Traceback (most recent call last):  File "<stdin>", line 1, in <module>UnicodeDecodeError: ''utf-8'' codec cant decode byte 0xad in position 0: invalid start byte>>> b"\xc2ad".decode("utf-8")Traceback (most recent call last):  File "<stdin>", line 1, in <module>UnicodeDecodeError: ''utf-8'' codec cant decode byte 0xc2 in position 0: invalid continuation byte

我用过了errors=''replace'',这似乎过去了。但我想了解一下,如果我尝试将其插入数据库中会发生什么。

编辑添加十六进制转储:

0036ae40  31 09 09 09 09 53 55 50  50 4c 45 4d 45 4e 54 41  |1....SUPPLEMENTA|0036ae50  4c 20 44 49 53 43 4c 4f  53 55 52 45 20 4f 46 20  |L DISCLOSURE OF |0036ae60  4e 4f 4e ad 43 41 53 48  20 49 4e 56 45 53 54 49  |NON.CASH INVESTI|0036ae70  4e 47 20 41 4e 44 20 46  49 4e 41 4e 43 49 4e 47  |NG AND FINANCING|0036ae80  20 41 43 54 49 56 49 54  49 45 53 3a 09 0a 50 72  | ACTIVITIES:..Pr|

答案1

小编典典

您的数据文件已损坏。如果该字符确实是U + 00AD SOFT
HYPHEN,那么您缺少一个0xC2字节:

>>> ''\u00ad''.encode(''utf8'')b''\xc2\xad''

在以0xAD结尾的所有可能的UTF-8编码中,软连字符确实最有意义。但是,它指示 可能 缺少其他字节的数据集。您碰巧碰到了一个重要事件。

我将返回此数据集的源,并验证下载时文件未损坏。否则,error=''replace''如果没有分隔符(制表符,换行符等)缺失,则使用是可行的解决方法。

另一种可能性是SEC实际上对文件使用了 不同的
编码。例如,在Windows代码页1252和Latin-1中,0xAD是软连字符的正确编码。确实,当我直接下载相同的数据集(警告,链接了大的ZIP文件)并打开时tags.txt,我无法将数据解码为UTF-8:

>>> open(''/tmp/2017q1/tag.txt'', encoding=''utf8'').read()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/.../lib/python3.6/codecs.py", line 321, in decode    (result, consumed) = self._buffer_decode(data, self.errors, final)UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xad in position 3583587: invalid start byte>>> from pprint import pprint>>> f = open(''/tmp/2017q1/tag.txt'', ''rb'')>>> f.seek(3583550)3583550>>> pprint(f.read(100))(b''1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH INVESTING AND FINANCING A'' b''CTIVITIES:\t\nProceedsFromSaleOfIn'')

文件中有两个这样的非ASCII字符:

>>> f.seek(0)0>>> pprint([l for l in f if any(b > 127 for b in l)])[b''SupplementalDisclosureOfNoncashInvestingAndFinancingActivitiesAbstract\t0'' b''001654954-17-000551\t1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH I'' b''NVESTING AND FINANCING ACTIVITIES:\t\n'', b''HotelKranichhheMember\t0001558370-17-001446\t1\t0\tmember\tD\t\tHotel Krani'' b''chhhe [Member]\tRepresents information pertaining to Hotel Kranichh\xf6h'' b''e.\n'']

Hotel Kranichh\xf6he
HotelKranichhöhe 被解码为Latin-1 。

文件中还有几对0xC1 / 0xD1对:

>>> f.seek(0)0>>> quotes = [l for l in f if any(b in {0x1C, 0x1D} for b in l)]>>> quotes[0].split(b''\t'')[-1][50:130]b''Temporary Payroll Tax Cut Continuation Act of 2011 (\x1cTCCA\x1d) recognized during th''>>> quotes[1].split(b''\t'')[-1][50:130]b''ributory defined benefit pension plan (the \x1cAetna Pension Plan\x1d) to allow certai''

我敢打赌那些实际上是U + 201C左双引号和U +
201D右双引号;注意1C1D部分。似乎他们的编码器似乎采用了UTF-16并去除了所有高字节,而不是正确地编码为UTF-8!

没有与Python中没有编解码器出货将编码''\u201C\u201D''b''\x1C\x1D'',使这一切更可能的是,美国证券交易委员会已经把事情弄糟了编码过程中的某个地方。实际上,还有0x13和0x14字符(可能是
enem 破折号)(U + 2013和U +
2014),以及几乎可以肯定是单引号的0x19字节(U +
2019)。完整图片所缺少的只是一个0x18字节来表示U +
2018。

如果我们假设编码已损坏,则可以尝试修复。以下代码将读取文件并解决引号问题,并假设其余数据不使用除引号之外的Latin-1之外的字符:

_map = {    # dashes    0x13: ''\u2013'', 0x14: ''\u2014'',    # single quotes    0x18: ''\u2018'', 0x19: ''\u2019'',    # double quotes    0x1c: ''\u201c'', 0x1d: ''\u201d'',}def repair(line, _map=_map):    """Repair mis-encoded SEC data. Assumes line was decoded as Latin-1"""    return line.translate(_map)

然后将其应用于您阅读的行:

with open(filename, ''r'', encoding=''latin-1'') as f:    repaired = map(repair, f)    fields = next(repaired).strip().split(''\t'')    for line in repaired:        yield process_tag_record(fields, line)

另外,解决您的已发布代码,使Python变得比预期更难工作。不要用codecs.open(); 那是已知问题的旧代码,并且比新的Python 3 I /
O层慢。只需使用open()。不要使用f.readlines(); 您无需在此处将整个文件读入列表。只需直接遍历文件即可:

def tags(filename):    """Yield Tag instances from tag.txt."""    with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f:        fields = next(f).strip().split(''\t'')        for line in f:            yield process_tag_record(fields, line)

如果process_tag_record还在选项卡上拆分,请使用一个csv.reader()对象,并避免手动拆分每一行:

import csvdef tags(filename):    """Yield Tag instances from tag.txt."""    with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f:        reader = csv.reader(f, delimiter=''\t'')        fields = next(reader)        for row in reader:            yield process_tag_record(fields, row)

如果process_tag_recordfields列表与其中的值组合在一起row以形成字典,请csv.DictReader()改用:

def tags(filename):    """Yield Tag instances from tag.txt."""    with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f:        reader = csv.DictReader(f, delimiter=''\t'')        # first row is used as keys for the dictionary, no need to read fields manually.        yield from reader

关于使用 Python 在 Pandas 中读取 CSV 文件时出现 UnicodeDecodeErrorpandas读取csv文件出错的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Anaconda中启动Python时的错误:UnicodeDecodeError: ''gbk'' codec can''t decode byte 0xaf in posit...、Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte、mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...、Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?的相关知识,请在本站寻找。

本文标签: