import zipfile, os
class Zip:
readme ="""
input_path,out_path, filelist,zipfilename
input_path,out_path,zipfilename type is str
"""
def __init__(self,input_path,out_path, filelist,filename,pathflag = '/'):
self.input_path = input_path
self.out_path = out_path
self.filelist = filelist
self.filename = filename
self._pathflag = pathflag
def check(self):
for date in [self.input_path, self.out_path, self.filename]:
for ci in date:
if type(ci) is str:
pass
else:
return -1
if type(self.filelist) is list:
pass
else:
return -1
def get_zip_file(self,input_path:str, filelist:list,):
"""
对目录进行深度优先遍历
:param input_path:
:param result:
:return:
"""
result = []
tmp_filelist = filelist
files = os.listdir(input_path)
for file in files:
if os.path.isdir(input_path + self._pathflag + file):
pass
else:
if file in filelist and file not in result:
result.append(input_path +self._pathflag + file)
tmp_filelist.remove(file)
if len(tmp_filelist) != 0:
for i in tmp_filelist:
print('not found file' +str(input_path) + str(i))
return -1
else:
return result
def zip_file_path(self):
"""
压缩文件
:param input_path: 压缩的文件夹路径
:param output_path: 解压(输出)的路径
:param output_name: 压缩包名称
:return:
"""
filelists_path = self.get_zip_file(self.input_path, self.filelist,)
if filelists_path != -1:
f = zipfile.ZipFile(self.out_path + self._pathflag + self.filename, 'w', zipfile.ZIP_DEFLATED)
for file in filelists_path:
f.write(file)
f.close()
return self.out_path + self.filename
return '获取压缩文件失败!'
def Zip(self):
if self.check() == -1:
return -1
print(self.zip_file_path())
if __name__ == '__main__':
Zip('C:\\Users\\11494\\Desktop\\emc\\','C:\\Users\\11494\\Desktop\\',['132.csv','125.csv','180 12.11.csv'],'ziptest.zip',pathflag='\\').Zip()
print(Zip.readme)