如何在python中提取gz文件

S A*_*rew 2 python gzip

我有一个.gz文件,里面有另一个文件。我需要提取压缩文件中的文件。

f = gzip.open(dest, 'rb')
Run Code Online (Sandbox Code Playgroud)

这只会打开文件,但我需要下载里面的特定文件,gz而不仅仅是打开gz文件。

这个问题已被标记为重复,我接受,但我还没有找到我们可以实际下载文件而不仅仅是阅读其内容的解决方案。提到的链接也是如此。

nor*_*ok2 6

您可以只打开两个文件,从文件中读取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)
Run Code Online (Sandbox Code Playgroud)

否则,您可以shutil按照How to unzip gz file using Python 中的建议使用

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)
Run Code Online (Sandbox Code Playgroud)

这两种解决方案都适用于 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)
Run Code Online (Sandbox Code Playgroud)