import uuid
import zipfile
import os
from tkinter import *
from tkinter.filedialog import askdirectory, askopenfilename,askopenfile,askopenfilenames,askopenfiles,asksaveasfile,asksaveasfilename
class Zip:
def unzip_file(self,zipfilename, unziptodir):
if not os.path.exists(unziptodir):
os.mkdir(unziptodir)
with zipfile.ZipFile(zipfilename) as zfobj:
for name in zfobj.namelist():
name = name.replace('\\', '/')
if name.endswith('/'):
os.mkdir(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir = os.path.dirname(ext_filename)
if not os.path.exists(ext_dir):
os.mkdir(ext_dir)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
def zip_file(self,rootname,fileNames):
with zipfile.ZipFile(os.path.join(rootname,str(uuid.uuid4())+".zip"),"w") as zf:
for path in fileNames:
print(path)
name = os.path.basename(path)
zf.write(path, name)
if os.path.isdir(path):
self.add_zip_file(path, os.listdir(path), name,zf)
def add_zip_file(self,rootname,fileNames,parentFilename,zf):
for name in fileNames:
path = os.path.join(rootname,name)
print(path)
zf.write(path,parentFilename+"/"+name)
if os.path.isdir(path):
self.add_zip_file(path,os.listdir(path),parentFilename+"/"+name,zf)
class UI:
def init(self):
self.root = Tk()
self.root.columnconfigure(0, weight=1)
self.path = StringVar()
Label(self.root, text="目标路径:").grid(row=0, column=0,sticky="nsew")
Entry(self.root, textvariable=self.path).grid(row=0, column=1, sticky="nsew")
Button(self.root, text="文件选择", command=self.selectFiles).grid(row=0, column=2, sticky="nsew")
Button(self.root, text="文件夹选择", command=self.selectDir).grid(row=0, column=3, sticky="nsew")
self.listb = Listbox(self.root)
self.listb.grid(row=1,column=0,columnspan=4, sticky="nsew")
self.ok_button = Button(self.root, text="保存到", command=self.ok).grid(row=2, column=0,columnspan=2, sticky="nsew")
self.cancel_button = Button(self.root, text="取消", command=self.root.quit).grid(row=2, column=2,columnspan=2, sticky="nsew")
self.texts = []
self.refreshFiles()
self.root.mainloop()
def selectFiles(self):
pathes = askopenfilenames()
self.path.set(pathes)
for path in pathes:
self.texts.append(path)
self.refreshFiles()
def selectDir(self):
path_ = askdirectory()
self.path.set(path_)
self.texts.append(path_)
self.refreshFiles()
def refreshFiles(self):
i = 1
self.listb.delete(0,END)
self.listb.insert(0,"选中的文件:")
for txt in self.texts:
self.listb.insert(i,txt)
i = i+1
def ok(self):
path_ = askdirectory()
Zip().zip_file(path_,self.texts)
self.texts.clear()
self.texts.append("成功!")
self.refreshFiles()
if __name__=="__main__":
UI().init()
用python写zip功能
最新推荐文章于 2023-11-20 16:49:38 发布