7z解压使用的py7zlib,因为是python2。
zip解压使用zipfile
import py7zlibfrom subprocess import callimport gzipimport osdef unzip_all_data(self, path):unzip_success = True# 遍历当前文件夹所有文件,解压所有压缩包for f in os.listdir(path):filePath = path + "/" + f# 如果是文件夹,跳过if os.path.isdir(filePath):continueif ".tar.gz" in f[-7:] or ".tgz" in f[-4:]:ret = call(["tar", "-xvzf", filePath, "-C", path])if (ret == 0):# 解压完成删除原压缩包call(["rm", filePath])else:return Falseelif ".zip" in f[-4:]:(ret, msg) = self.unzip(filePath, path)if (ret == 0):# 解压完成删除原压缩包call(["rm", filePath])else:return Falseelif ".gz" in f[-3:]:(ret, msg) = self.ungz(path, f)if ret:# 解压完成删除原压缩包call(["rm", filePath])else:return Falseelif ".7z" in f[-3:]:print('55555', f)(ret, msg) = self.un7z(path, filePath)if ret:# 解压完成删除原压缩包call(["rm", filePath])else:return False# 再次查看本文件夹是否存在压缩包,防止多层压缩包if self.has_zip_file(path):unzip_success = self.unzip_all_data(path)if not unzip_success:return unzip_success# 遍历所有文件夹,递归每个文件夹for f in os.listdir(path):dirPath = path + "/" + fif os.path.isdir(dirPath):# __MACOSX文件夹是mac压缩文件时产生的缓存文件,无需处理if f == "__MACOSX":continueunzip_success = self.unzip_all_data(dirPath)if not unzip_success:return unzip_successreturn unzip_successdef has_zip_file(self, path):for f in os.listdir(path):if ".tar.gz" in f[-7:] or ".tgz" in f[-4:] or ".zip" in f[-4:] or ".gz" in f[-3:] or ".7z" in f[-3:]:return Truereturn Falsedef un7z(self, path, filePath):try:fp = open(filePath,'rb')#生成一个archive对象archive = py7zlib.Archive7z(fp)#读取文件中所有的文件名names = archive.getnames()#根据文件名返回文件的archiveFile类for name in names:member = archive.getmember(name)#读取文件的所有数据data = member.read()open(path + "/" + name, "w+").write(data)if fp:fp.close()return (True, "")except Exception as e:print("un7z", str(e))return (False, str(e))def ungz(self, path, f):try:# 获取文件的名称f_name = f.replace(".gz", "")#创建gzip对象g_file = gzip.GzipFile(path + "/" + f)#gzip对象用read()打开后,写入open()建立的文件里。open(path + '/' + f_name, "w+").write(g_file.read())g_file.close()return (True, "")except Exception as e:print("ungz", str(e))return (False, str(e))def unzip(self, source, dest):try:from zipfile import ZipFilezipSource = ZipFile(source, 'r')zipSource.extractall(dest)zipSource.close()return (0, "")except Exception as e:print("unzip", str(e))return (1, str(e))
如果觉得《python解压多层压缩包 兼容tar.gz .tgz .zip .7z .gz》对你有帮助,请点赞、收藏,并留下你的观点哦!