在Python中设置“encoding”gzip.open()似乎没有

2024-09-27 21:30:29 发布

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

即使我试图用python的gzip.open(),它似乎总是使用cp1252.py对文件内容进行编码。 我的代码:

with gzip.open('file.gz', 'rt', 'cp1250') as f:
    content = f.read()

回应:

File "C:\Python34\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 52893: character maps to undefined


Tags: 文件代码inpy内容编码withopen
1条回答
网友
1楼 · 发布于 2024-09-27 21:30:29

Python 3.x版

gzip.opendefined为:

gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

因此,gzip.open('file.gz', 'rt', 'cp1250')向它发送以下参数: -文件名='文件.gz' -模式='rt' -压缩机液位='cp1250'

这显然是错误的,因为其目的是使用“cp1250”编码。 encoding参数可以作为第四个位置参数或关键字参数发送:

gzip.open('file.gz', 'rt', 5, 'cp1250')  # 4th positional argument

gzip.open('file.gz', 'rt', encoding='cp1250') # keyword argument

Python 2.x版

{{a2>在读取^数据之后^不接受^文本:

^{pr2}$

相关问题 更多 >

    热门问题