【问题标题】:Python: How to decompress a GZIP file to an uncompressed file on disk?Python:如何将 GZIP 文件解压缩为磁盘上的未压缩文件?
【发布时间】:2018-07-06 02:12:35
【问题描述】:

我想在 Python 脚本中模拟 gzip -d <file.gz> 的行为。

压缩后的 GZIP 文件被解压并写入为与原始 GZIP 文件同名的文件,不带 .gz 扩展名。

file.abc.gz --> 文件.abc

使用 gzip 库如何做到这一点并不明显,文档中的所有示例都是用于压缩数据数组,我还没有从研究中找到一个好的示例。

编辑

我已经尝试使用 tarfile 模块进行以下操作,但不幸的是它不起作用,我认为因为 GZIP 文件不是使用 tar 创建的。

# get the zipped file's contents list, extract the file
with tarfile.TarFile(local_zipped_filename) as tar_file:

    # list the contents, make sure we only extract the expected named file
    members = tar_file.getmembers()
    for member in members:
        if member.name == filename_unzipped:
            members_to_extract = [member]
            tar_file.extractall(path=destination_dir, members=members_to_extract)
            break   # we've extracted our file, done

【问题讨论】:

    标签: python python-3.x gzip


    【解决方案1】:

    您可以使用 tarfile 模块来满足您的要求。

    示例:

    import tarfile
    tar = tarfile.open("test.tar.gz")
    tar.extractall()
    tar.close()
    

    【讨论】:

    • 仅当 OP 的文件实际上是 .tar.gz 格式时才为真,他们尚未指定。
    • 好像是这样,当我尝试使用这种方法时出现错误:tarfile.ReadError: invalid header..
    【解决方案2】:
    import gzip, shutil
    
    with gzip.open('file.abc.gz', 'r') as f_in, open('file.abc', 'wb') as f_out:
      shutil.copyfileobj(f_in, f_out)
    

    gzip module 提供了一个类文件对象,其中包含 gzip 文件的解压缩内容; shutil module 为将内容从一个类似文件的对象复制到另一个对象提供了方便的助手。


    这是the official documentation中给出的示例的简单反转:

    如何 GZIP 压缩现有文件的示例:

    import gzip
    import shutil
    with open('/home/joe/file.txt', 'rb') as f_in:
        with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    

    【讨论】:

    • 非常有帮助的答案,这似乎像宣传的那样有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多