前今天没事写了个解压文件的api.

#!/usr/bin/env python
#author:zhaojianxi
#coding:utf-8

import zipfile
import os
class ZipfileApi(object):
def compressionFile(self,filepath,zipname,format):
if not os.path.isdir(filepath):
zipName=zipname+"."+format
zipName=zipName.decode("utf-8")
filepath=filepath.decode("utf-8")
root,file=os.path.split(filepath)
#os.chdir(rootname)
f = zipfile.ZipFile(zipName, 'w', zipfile.ZIP_DEFLATED)
f.write(file)
f.close()
else:
zipName=zipname+"."+format
zipName=zipName.decode("utf-8")
filepath=filepath.decode("utf-8")
f = zipfile.ZipFile(zipName, 'w', zipfile.ZIP_DEFLATED)
current=os.path.abspath(os.path.join(filepath,".."))
os.chdir(current)
filepath=filepath.replace("\\",'/')
currentRoot=filepath.split("/")[-1]
print currentRoot
for root, dirs, files in os.walk(currentRoot):
for file in files:
f.write(os.path.join(root,file))
f.close()
def unpackFile(self,filepath,savepath=''):
filepath=filepath.decode("utf-8")
savepath=savepath.decode("utf-8")
f = zipfile.ZipFile(filepath,'r')
for file in f.namelist():
f.extract(file,savepath)


zip1=ZipfileApi()
zip1.compressionFile(r"C:\Users\Administrator\Desktop\root\qwert",r"D:/root","rar")
#zip1.unpackFile(r"D:\root.rar",r"C:\Users\Administrator\Desktop")

1,首先,ZipfileApi()实例化;
2,compressionFile,传递压缩路径(文件或目录),压缩文件名,压缩格式等
3,unpackFile,解压文件名,解压路径

再附上一个可以再txt里寻找密码的小案例。

#coding:utf-8
# zip文件
import zipfile
import os
# 对zip文件进行密码测试,成功返回True,失败返回False
def testZip(filePathname,password):
# 判断目录是否存在
#filePathname=filePathname.decode("utf-8")

if os.path.exists(filePathname)==False:
print("文件"+filePathname+"不存在")
return False
#print filePathname
zfile=zipfile.ZipFile(filePathname,"r")



try:
zfile.extractall(pwd=password.encode('utf-8'))
return True
except Exception as e:
#print(e)
return False


# 入口函数
def main():
passFile=open(r'C:\Users\Administrator\Desktop\mayaApi\pass.txt')

for line in passFile.readlines():
password=line.strip()
pw=password
#print password
if testZip(r'C:\Users\Administrator\Desktop\mayaApi\pass.zip',pw)==True:
passFile.close()
passFile=open(r'C:\Users\Administrator\Desktop\mayaApi\pass.txt','a+')
print pw
passFile.write('\n'+pw)



passFile.close()




# Kickoff Start
main()