Python:在.zip中解压缩和解压缩.Z文件

时间:2013-08-28 16:52:34

标签: python

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

我使用Import gzip和Import zlib在python中尝试过这个。

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

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

1 个答案:

答案 0 :(得分:3)

您需要实际使用某种类型的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
相关问题