将文件与Tkinter中的文本输入分开压缩文件

时间:2019-07-08 11:30:13

标签: python tkinter zip

我在一个文件夹中装载了大量数据库文件。它基本上看起来像这样: 对于数据库ABC,我具有以下文件:

ABC.ase
ABC.dde
ABC.lpk
ABC.koi
ABCIPS.lip

对于数据库JDE,我具有以下文件:

JDE.ase
JDE.dde
JDE.lpk
JDE.koi
JDESFF.lip

对于每个数据库,我需要将其中一些数据库压缩到一个文件中,即:

ABC.zip包含除IPS文件之外的所有文件,因此:

ABC.ase
ABC.dde
ABC.lpk
ABC.koi

这是我的代码:

import tkinter as tki
import zipfile
import os
from tkinter import messagebox

class App(object):

    def __init__(self):
        self.root = tki.Tk()
        self.root.title('Database Zipper')

        # create a Frame for the Text and Scrollbar
        txt_frm = tki.Frame(self.root, width=300, height=600)
        txt_frm.pack(fill="both", expand=True)

        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)

        # implement stretchability
        txt_frm.grid_rowconfigure(0, weight=1)
        txt_frm.grid_columnconfigure(0, weight=1)

        # create a Text widget
        self.txt = tki.Text(txt_frm, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

        # create a Scrollbar and associate it with txt
        scrollb = tki.Scrollbar(txt_frm, command=self.txt.yview)
        scrollb.grid(row=0, column=1, sticky='nsew')
        self.txt['yscrollcommand'] = scrollb.set
        tki.Button(txt_frm, text='ZIP', command=self.retrieve_input).grid(row=1, column=0)

    def retrieve_input(self):
        #zipping + filtering files
        cel = c:\DBS
        cip = c:\ZIP
        cippath = os.listdir(cip)

        lines = self.txt.get("1.0", tki.END).splitlines()
        filestozip = []
        for file in lines:
            basename = os.path.splitext(file)[0]
            filestozip.append(basename)
        for basename in filestozip:
            os.chdir(cip)
            with zipfile.ZipFile(cel + basename + '.zip', 'w', compression=zipfile.ZIP_DEFLATED) as myzip:
                for file in cippath:
                    if 'IPS' in file:
                        continue
                    if any(x in file for x in filestozip):
                        myzip.write(file)

        messagebox.showinfo("Success", "Files have been zipped successfully")

app = App()
app.root.mainloop()

当我在文本框中只键入一行时,它工作得很好,但是,当其中有多个条目时,例如: ABC JDE

最后我得到两个压缩文件ABC.zipJDE.zip,每个压缩文件中都包含ABC和JDE文件。我该如何预防?

谢谢!

0 个答案:

没有答案