如何在python中提取gz文件

问题描述 投票:1回答:2

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

f = gzip.open(dest, 'rb')

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

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

python gz
2个回答
2
投票

您可以打开两个文件,从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)
        d_file.write(block)

否则,您可以使用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)

这两种解决方案都适用于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)

0
投票

我已经解决了这个问题:

f = gzip.open(dest, 'r')
file_content = f.read()
file_content = file_content.decode('utf-8')
f_out = open('file', 'w+')
f_out.write(file_content)
f.close()
f_out.close()

dest是gz的文件

© www.soinside.com 2019 - 2024. All rights reserved.