【发布时间】:2013-02-27 11:03:35
【问题描述】:
我想使用 urllib 下载一个文件,并在保存前解压内存中的文件。
这就是我现在拥有的:
response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO()
compressedFile.write(response.read())
decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
outfile = open(outFilePath, 'w')
outfile.write(decompressedFile.read())
这最终会写入空文件。我怎样才能达到我所追求的目标?
更新答案:
#! /usr/bin/env python2
import urllib2
import StringIO
import gzip
baseURL = "https://www.kernel.org/pub/linux/docs/man-pages/"
# check filename: it may change over time, due to new updates
filename = "man-pages-5.00.tar.gz"
outFilePath = filename[:-3]
response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO(response.read())
decompressedFile = gzip.GzipFile(fileobj=compressedFile)
with open(outFilePath, 'w') as outfile:
outfile.write(decompressedFile.read())
【问题讨论】:
-
解压到磁盘有什么问题?
-
我正在解压缩到磁盘,只是永远不要让压缩的字节接触磁盘。
-
compressedFile有没有得到过再见? -
是的,在更新版本中
-
不相关:您可以使用
shutil.copyfileobj(decompressed_file, outfile)逐块保存文件,而无需将其加载到内存中。
标签: python file gzip urllib2 stringio