【问题标题】:How to extract a gz file in python如何在python中提取gz文件
【发布时间】:2018-09-14 13:19:02
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是否希望将其保存在某个地方(即您希望基本上在 Python 中实现 gunzip)?
  • @norok2 是的,将文件解压缩到任何目标位置
  • @Meyi 我已经检查了那个链接。没有答案,我们可以实际下载文件。请让我知道您指的是哪个答案。?谢谢
  • @SAndrew Meyi 发布的链接显示了如何解压缩 .gz 文件。你真的想做点别的吗?你提到下载 - 你的意思是你想从一些网络服务器下载文件?

标签: python gzip


【解决方案1】:

您可以只打开两个文件,从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)

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

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)

【讨论】:

  • 与 shell 中的原生 gzip 命令相比,它的性能如何?
  • @alper 可能更糟,因为 gzip 也在做同样的事情,但本质上是在 C 中。
【解决方案2】:

我已经解决了这样的问题:

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 的文件

【讨论】:

  • 您的解决方案不是最理想的,因为您可能会遇到大文件的内存问题。此外,这将比它可能的要慢,因为您正在执行不必要的解码。
猜你喜欢
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多