在 Python 的 gzip.open() 中设置 'encoding' 似乎不起作用
Setting up 'encoding' in Python's gzip.open() doesn't seem to work
即使我尝试在 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
Python 3.x
gzip.open
是 defined 为:
gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
因此,gzip.open('file.gz', 'rt', 'cp1250')
将这些参数发送给它:
- 文件名 = 'file.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
Python 2 version of gzip.open
不接受 encoding
参数并且它不接受文本模式,所以解码必须在读取数据后显式完成:
with gzip.open('file.gz', 'rb') as f:
data = f.read()
decoded_data = data.decode('cp1250')
即使我尝试在 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
Python 3.x
gzip.open
是 defined 为:
gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
因此,gzip.open('file.gz', 'rt', 'cp1250')
将这些参数发送给它:
- 文件名 = 'file.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
Python 2 version of gzip.open
不接受 encoding
参数并且它不接受文本模式,所以解码必须在读取数据后显式完成:
with gzip.open('file.gz', 'rb') as f:
data = f.read()
decoded_data = data.decode('cp1250')