7z解压使用的py7zlib,因为是python2。
zip解压使用zipfile
import py7zlib
from subprocess import call
import gzip
import os
def unzip_all_data(self, path):
unzip_success = True
# 遍历当前文件夹所有文件,解压所有压缩包
for f in os.listdir(path):
filePath = path + "/" + f
# 如果是文件夹,跳过
if os.path.isdir(filePath):
continue
if ".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 False
elif ".zip" in f[-4:]:
(ret, msg) = self.unzip(filePath, path)
if (ret == 0):
# 解压完成删除原压缩包
call(["rm", filePath])
else:
return False
elif ".gz" in f[-3:]:
(ret, msg) = self.ungz(path, f)
if ret:
# 解压完成删除原压缩包
call(["rm", filePath])
else:
return False
elif ".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 + "/" + f
if os.path.isdir(dirPath):
# __MACOSX文件夹是mac压缩文件时产生的缓存文件,无需处理
if f == "__MACOSX":
continue
unzip_success = self.unzip_all_data(dirPath)
if not unzip_success:
return unzip_success
return unzip_success
def 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 True
return False
def 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 ZipFile
zipSource = ZipFile(source, 'r')
zipSource.extractall(dest)
zipSource.close()
return (0, "")
except Exception as e:
print("unzip", str(e))
return (1, str(e))