【发布时间】:2021-07-08 18:40:27
【问题描述】:
我正在尝试下载文件并将其写入磁盘,但不知何故我迷失在编码解码领域。
from urllib.request import urlopen
url = "http://export.arxiv.org/e-print/supr-con/9608001"
with urllib.request.urlopen(url) as response:
data = response.read()
filename = 'test.txt'
file_ = open(filename, 'wb')
file_.write(data)
file_.close()
这里的数据是一个字节串。如果我检查文件,我会发现一堆奇怪的字符。我试过了
import chardet
the_encoding = chardet.detect(data)['encoding']
但这会导致无。所以我真的不知道我下载的数据是怎么编码的?
如果我只是在浏览器中输入“http://export.arxiv.org/e-print/supr-con/9608001”,它会下载一个我可以使用文本编辑器查看的文件,这非常好。 tex 文件。
【问题讨论】:
-
您的
data包含文件签名b'\x1f\x8b'即GZIP 压缩文件... -
检查
print( response.headers ),您会看到Content-Encoding: x-gzip,这表明它发送使用gzip压缩的数据(以便更快地发送),您必须解压缩它。当您在浏览器中运行 URL 时,浏览器会自动为您解压缩。