【问题标题】:Python: Unzipping and decompressing .Z files inside .zipPython:解压和解压 .zip 中的 .Z 文件
【发布时间】:2013-08-28 16:52:33
【问题描述】:

我正在尝试解压缩一个 Alpha.zip 文件夹,其中包含一个 Beta 目录,其中包含一个 Gamma 文件夹,其中包含 a.Z、b.Z、c.Z、d.Z 文件。使用 zip 和 7-zip,我能够提取存储在 .Z 文件中的所有 a.D、b.D、c.D、d.D 文件。

我在 python 中使用 Import gzip 和 Import zlib 进行了尝试。

import sys
import os
import getopt
import gzip
f = open('a.d.Z','r')
file_content = f.read()
f.close()

我不断收到各种错误,包括:这不是一个 zip 文件,返回 codecs.charmap_encode(input self.errors encoding_map) 0。关于如何编码的任何建议?

【问题讨论】:

    标签: python


    【解决方案1】:

    您实际上需要使用某种 zip 库。现在你正在导入gzip,但你没有用它做任何事情。尝试查看gzip documentation 并使用该库打开文件。

    gzip_file = gzip.open('a.d.Z') # use gzip.open instead of builtin open function
    file_content = gzip_file.read()
    

    根据您的评论进行编辑:您不能只使用任何压缩库打开各种压缩文件。由于您有一个.Z 文件,因此您可能希望使用zlib 而不是gzip,但由于扩展名只是约定,只有您才能确定文件的压缩格式。使用zlib ,改为执行以下操作:

    # Note: untested code ahead!
    import zlib
    with open('a.d.Z', 'rb') as f: # Notice that I open this in binary mode
        file_content = f.read() # Read the compressed binary data
        decompressed_content = zlib.decompress(file_content) # Decompress
    

    【讨论】:

    • #!/usr/bin/python33 import sys import os import getopt import gzip f = gzip.open('a.d.Z') f_content = f.read() 我不断收到的错误是 f_content = f .read() 文件“C:\Python33\lib\gzip.py”,第 360 行,在读取 self._read(readsize) 文件“C:\Python33\lib\gzip.py”,第 441 行,在 _read self. _read_gzip_header() 文件“C:\Python33\lib\gzip.py”,第 290 行,在 _read_gzip_header 中引发 IOError('Not a gzipped file') OSError: Not a gzipped file
    • @DDS 这看起来像是一条非常简单的错误消息...您尝试打开的文件不是 gzip 文件。你知道用什么协议来压缩它吗? gzip 仅适用于 gzip 文件。由于扩展名是.Z,您可能想要使用zlib。您必须为您拥有的特定文件使用正确的解压缩库。
    猜你喜欢
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多