【问题标题】:UnicodeDecodeError: 'charmap' codec can't decode byte 0x81UnicodeDecodeError:“charmap”编解码器无法解码字节 0x81
【发布时间】:2018-12-27 06:55:06
【问题描述】:

我正在使用 Python(3.6) 开发一个项目,其中我需要从包含数千个文本文件的目录中读取文本文件,然后我需要对它们进行一些分析并将结果上传到谷歌云存储. 出现编码错误。

这是我尝试过的:

来自views.py

def predict_encoding(file_path, n_lines=60):
    '''Predict a file's encoding using chardet'''
    import chardet

    # Open the file as binary data
    with open(file_path, 'rb') as f:
        # Join binary lines for specified number of lines
        rawdata = b''.join([f.read() for _ in range(n_lines)])
    encoding = chardet.detect(rawdata)['encoding']
    print('Default encoding is: {}'.format(encoding))
    if encoding is None:
        rawdata.decode('utf8').encode('ascii', 'ignore')
        print('updated decoding is: {}'.format(chardet.detect(rawdata)['encoding']))
    return chardet.detect(rawdata)['encoding']


encoding = predict_encoding(text_path)
txt = Path(text_path).read_text(encoding=encoding)

但对于某些文件(请参阅下面的示例文件:),它会返回如下错误:

/Users/abdul/Downloads/to_save/cert2.txt

默认编码为:无

更新的解码是:无

返回 codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError:“charmap”编解码器无法解码位置 339 中的字节 0x81:字符映射到

这是返回此错误的示例: https://textuploader.com/d8ec5

【问题讨论】:

  • 尝试用ingore进行Latin-1编码
  • 这里没有任何变化!

标签: python encoding character-encoding pythonpath


【解决方案1】:

您尝试分析的文件是图像(文件头中的Compress (tm) Xing Technology Corp)。因此,在检查编码之前,您需要检查文件是否为二进制文件。您可以为此使用following solution

>>> is_binary_string(open(text_path, 'rb').read(1024))
True

【讨论】:

  • 它在 Python 的 shell 中运行良好,但在 Django 文件中它返回错误:TypeError: translate() takes exactly one argument (2 given)
猜你喜欢
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 2017-02-06
  • 2021-05-06
  • 2021-04-11
  • 2020-02-02
  • 1970-01-01
相关资源
最近更新 更多