Use zipfile to create a file compression tool

In this blog post, we will use the wxPython module to create a simple file compression tool. The tool has a Graphical User Interface (GUI) that can select files in a source folder, compress them into a ZIP file, and save the compressed file to a target folder.
C:\pythoncode\new\zipmultifile.py
insert image description here

Preparation

Before starting, make sure you have installed the wxPython module. You can use the following command to install:

pip install wxPython

Create a GUI interface

First, we import the required modules and create a MyFrameclass to represent our application window.

import wx
import wx.lib.agw.multidirdialog as MDD
import os
import datetime
import zipfile

class MyFrame(wx.Frame):
    # ...

In MyFramethe constructor of the class, we created the various controls on the window, including the button to select the source folder, the Listbox to display the file list, the button to select the target folder, and the Zip button. We also define two instance variables source_folderand target_folderto store the paths of the selected source and destination folders respectively.

Implement event handlers

We bind on_select_source_folderthe method for the select source folder button, which will open the folder selection dialog and load the file list into the Listbox after the selection is complete.

def on_select_source_folder(self, event):
    dlg = MDD.MultiDirDialog(self, title="选择源文件夹")
    if dlg.ShowModal() == wx.ID_OK:
        self.source_folder = dlg.GetPaths()[0]
        self.load_files()
    dlg.Destroy()

Similarly, we bind on_select_target_folderthe method for the select target folder button, which opens the folder selection dialog and stores the path of the target folder when the selection is complete.

def on_select_target_folder(self, event):
    dlg = MDD.MultiDirDialog(self, title="选择目标文件夹")
    if dlg.ShowModal() == wx.ID_OK:
        self.target_folder = dlg.GetPaths()[0]
    dlg.Destroy()

Finally, we bind on_zipthe method to the Zip button, which checks to see if the files to be compressed are selected, and if so, creates a ZIP file, adds the selected files to the zip file, and saves it to the target folder.

def on_zip(self, event):
    selected_files = [self.listbox.GetString(i) for i in self.listbox.GetSelections()]
    if len(selected_files) == 0:
        wx.MessageBox("请先选择要压缩的文件!", "错误", wx.OK | wx.ICON_ERROR)
        return

    now = datetime.datetime.now()
    zip_filename = os.path.join(self.target_folder, now.strftime("%Y%m%d") + ".zip")

    with zipfile.ZipFile(zip_filename, 'w') as zipf:
        for file in selected_files:
            file_path = os.path.join(self.source_folder, file)
            zipf.write(file_path, file)

    wx.MessageBox("文件已成功压缩为 ZIP 文件!", "成功", wx.OK | wx.ICON_INFORMATION)

start the application

Finally, we create an instance of the wxPython application and display the window.

app = wx.App()
frame = MyFrame(None, title="ZIP 文件压缩")
frame.Show()
app.MainLoop()

all codes

import wx
import wx.lib.agw.multidirdialog as MDD
import os
import datetime
import zipfile

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(600, 400))
        
        self.panel = wx.Panel(self)
        
        self.source_folder_btn = wx.Button(self.panel, label="选择源文件夹", pos=(10, 10))
        self.source_folder_btn.Bind(wx.EVT_BUTTON, self.on_select_source_folder)
        
        self.listbox = wx.ListBox(self.panel, pos=(10, 50), size=(200, 300), style=wx.LB_MULTIPLE)
        
        self.target_folder_btn = wx.Button(self.panel, label="选择目标文件夹", pos=(250, 10))
        self.target_folder_btn.Bind(wx.EVT_BUTTON, self.on_select_target_folder)
        
        self.zip_btn = wx.Button(self.panel, label="Zip", pos=(500, 10))
        self.zip_btn.Bind(wx.EVT_BUTTON, self.on_zip)
        
        self.source_folder = ""
        self.target_folder = ""
        
    def on_select_source_folder(self, event):
        dlg = MDD.MultiDirDialog(self, title="选择源文件夹")
        if dlg.ShowModal() == wx.ID_OK:
            self.source_folder = dlg.GetPaths()[0]
            self.load_files()
        dlg.Destroy()
        
    def load_files(self):
        self.listbox.Clear()
        files = os.listdir(self.source_folder)
        for file in files:
            self.listbox.Append(file)
        
    def on_select_target_folder(self, event):
        dlg = MDD.MultiDirDialog(self, title="选择目标文件夹")
        if dlg.ShowModal() == wx.ID_OK:
            self.target_folder = dlg.GetPaths()[0]
        dlg.Destroy()
        
    def on_zip(self, event):
        selected_files = [self.listbox.GetString(i) for i in self.listbox.GetSelections()]
        if len(selected_files) == 0:
            wx.MessageBox("请先选择要压缩的文件!", "错误", wx.OK | wx.ICON_ERROR)
            return
        
        now = datetime.datetime.now()
        zip_filename = os.path.join(self.target_folder, now.strftime("%Y%m%d") + ".zip")
        
        with zipfile.ZipFile(zip_filename, 'w') as zipf:
            for file in selected_files:
                file_path = os.path.join(self.source_folder, file)
                zipf.write(file_path, file)
        
        wx.MessageBox("文件已成功压缩为 ZIP 文件!", "成功", wx.OK | wx.ICON_INFORMATION)
        

app = wx.App()
frame = MyFrame(None, title="ZIP 文件压缩")
frame.Show()
app.MainLoop()

Summarize

By using the wxPython module, we have created a simple and functional file compression tool. The tool has an intuitive graphical user interface that allows easy selection of source and destination folders and compresses the selected files into ZIP format. You can modify and expand the code according to your own needs to meet more complex compression needs.

Hope this blog content is helpful to you. If you have any questions or need further guidance, please feel free to ask. Happy programming!

Guess you like

Origin blog.csdn.net/winniezhang/article/details/132609077