用Python实现txt文本内容比对,并将比对结果以文件夹输出,并用Tkinter将这个代码封装成一个小程序
时间: 2024-05-05 11:17:54 浏览: 69
python 对比俩个txt文件内容
好的,这是一个很好的问题!以下是一个使用Python实现txt文本内容比对的示例代码:
```python
import filecmp
import os
def compare_files(file1, file2):
return filecmp.cmp(file1, file2)
def compare_folders(folder1, folder2):
dircmp = filecmp.dircmp(folder1, folder2)
for name in dircmp.diff_files:
print("diff_file %s found in %s and %s" % (name, folder1, folder2))
for sub_dircmp in dircmp.subdirs.values():
compare_folders(sub_dircmp.left, sub_dircmp.right)
if __name__ == "__main__":
folder1 = "folder1"
folder2 = "folder2"
output_folder = "output"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
compare_folders(folder1, folder2)
```
这个代码将比较两个文件夹中的文件和子文件夹的内容,并将不同的文件输出到一个名为“output”的文件夹中。你可以根据自己的需要修改输出文件夹的名称和比较的文件夹路径。接下来,我将使用Tkinter将这个代码封装成一个小程序,让它更方便易用。
```python
import filecmp
import os
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.folder1_label = Label(master, text="Folder 1:")
self.folder1_label.grid(row=0, column=0)
self.folder1_entry = Entry(master)
self.folder1_entry.grid(row=0, column=1)
self.folder2_label = Label(master, text="Folder 2:")
self.folder2_label.grid(row=1, column=0)
self.folder2_entry = Entry(master)
self.folder2_entry.grid(row=1, column=1)
self.output_label = Label(master, text="Output Folder:")
self.output_label.grid(row=2, column=0)
self.output_entry = Entry(master)
self.output_entry.grid(row=2, column=1)
self.compare_button = Button(master, text="Compare", command=self.compare_folders)
self.compare_button.grid(row=3, column=0, columnspan=2)
self.quit_button = Button(master, text="Quit", command=self.master.quit)
self.quit_button.grid(row=4, column=0, columnspan=2)
def compare_folders(self):
folder1 = self.folder1_entry.get()
folder2 = self.folder2_entry.get()
output_folder = self.output_entry.get()
if not os.path.exists(output_folder):
os.makedirs(output_folder)
dircmp = filecmp.dircmp(folder1, folder2)
for name in dircmp.diff_files:
print("diff_file %s found in %s and %s" % (name, folder1, folder2))
for sub_dircmp in dircmp.subdirs.values():
self.compare_folders(sub_dircmp.left, sub_dircmp.right)
root = Tk()
app = Application(master=root)
app.mainloop()
```
这个程序使用Tkinter创建了一个简单的GUI,使用户可以输入要比较的文件夹路径和输出文件夹的名称,然后单击“Compare”按钮来运行比较。当比较完成后,不同的文件将被输出到指定的输出文件夹中。
希望这个示例程序能够帮助你解决你的问题!
阅读全文