我有一个.gz
文件,里面还有另一个文件。我需要将文件解压缩到压缩文件中。
f = gzip.open(dest, 'rb')
这只会打开文件,但我需要下载其中的特定文件,gz
而不仅仅是打开gz
文件。
我接受了这个问题,并将其标记为重复,但是我没有找到一个可以实际下载文件而不只是读取其内容的解决方案。提到的链接也是如此。
您可以打开两个文件,从文件中读取gzipped
并写入另一个文件(以块为单位,以避免阻塞内存)。
import gzip
def gunzip(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
while True:
block = s_file.read(block_size)
if not block:
break
else:
d_file.write(block)
否则,您可以shutil
按照如何使用Python解压缩gz文件中的建议使用:
import gzip
import shutil
def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
shutil.copyfileobj(s_file, d_file, block_size)
两种解决方案都可以在Python 2和3中使用。
在性能方面,至少在我的系统上,它们基本上是等效的:
%timeit gunzip(source_filepath, dest_filepath)
# 129 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit gunzip_shutil(source_filepath, dest_filepath)
# 132 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句