【发布时间】:2017-12-18 16:02:13
【问题描述】:
你好 :) 我有一个大的 bin 文件,它已被 gzip 压缩(所以它是 blabla.bin.gz)。
我需要解压并写入一个ASCII格式的txt文件。 这是我的代码:
import gzip
with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f:
file_content = f.read()
file_content.decode("ascii")
output = open("new_file.txt", "w", encoding="ascii")
output.write(file_content)
output.close()
但我得到了这个错误:
file_content.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 19: ordinal not in range(128)
我对 Python 并不陌生,但格式/编码问题一直是我最大的弱点 :(
拜托,你能帮帮我吗?
谢谢!!!
【问题讨论】:
-
考虑过 gzip 压缩文件可能是 UTF8 或 unicode 或其他任何格式的文件吗?你能检查一下吗? 128位ASCII没有处理的东西?只是为了咯咯笑:尝试
encoding='utf-8',或只是file_content.decode("utf-8")- 更好地习惯 utf-8 - 现在它是一种默认值。 -
file_content.decode('cp1252')有效吗?0x94是 cp1252 中的右大括号双引号,是 Windows 系统上常见的编码。 -
@PatrickArtner (1) ValueError: 二进制模式不支持参数“编码”(我在二进制模式下使用“rb”); (2) 我必须创建一个 ascii 文件。 :(
-
@usr2564301:注意,cp1252 接近 Latin1 但不是,只有 Latin1 保证 decode/encode 是无操作的。
标签: python ascii decode encode gzip