0
点赞
收藏
分享

微信扫一扫

python学习-实现对比文件输出html

乱世小白 2023-04-01 阅读 122

在网络配置过程中,经常要对比两个配置文的差异,常用的一些文档编辑器带有文本对比的功能,如notepadd++,等。但是这些大部分都要收费或者安装其他插件,不是很友好,linux上自带diff可以对比,但是一般网工都linux不太熟悉。而且操蛋的是在客户都这里,给你的终端装了沙盒,禁止安装 其他的文本的编辑器,也不能联网,还好可以装python,所以就像想写一个python的图形化对比工具

需求:

  • 基于python3编写,不依赖其他第三方模块
  • 基于图形化,操作简单

采用去如下办法解决

  • 采用python3自带的difflib模块,对比文件结果输出为html
  • 采用python3自带的tk图形框架

以下是相关代码

import difflib
import tkinter as tk
import tkinter.filedialog  #文件输入框
import tkinter.messagebox #提示框

class WINDOW():

    def __init__(self):
        '''
        构造tk窗口
        '''
        self.window=tk.Tk()
        self.window.title('文件对比') #设置标题
        self.window.geometry("650x200") #设置大小
        self.label=tk.Label(self.window,text="请选择需要对比的文件:",fg='blue',font=("Arial",12)).place(x=30,y=30) #主窗口添加标签
        self.l1=tk.Label(self.window,text="源文件:",font=("Arial",12)).place(x=30,y=80)
        self.l2=tk.Label(self.window,text="目标文件:",font=("Arial",12)).place(x=30,y=110)
        #主窗口添加文本框
        self.txt_path1=tk.StringVar()
        self.text1=tk.Entry(self.window,textvariable=self.txt_path1,show=None,width=60)
        self.txt_path2 = tk.StringVar()
        self.text2 = tk.Entry(self.window, textvariable=self.txt_path2, show=None, width=60)
        self.text1.place(x=120,y=80)
        self.text2.place(x=129,y=110)
        #主窗口添加命令按钮
        self.button1=tk.Button(self.window,width=8,height=1,text="选择文件",bg="skyblue",command=self.button1).place(x=550,y=80)
        self.button2=tk.Button(self.window,width=8,height=1,text="选择文件",bg="skyblue",command=self.button2).place(x=550,y=110)
        self.button3= tk.Button(self.window, width=8, height=1, text="比较文件", fg="red",bg="orange", command=self.Diff).place(
            x=550, y=150)
        self.window.mainloop()


    def button1(self):
			  #按钮函数,使用tk.filedialog.askopenfilename()打开文件
        self.file1=tk.filedialog.askopenfilename()
        self.txt_path1.set(self.file1)


    def button2(self):

        self.file2 = tk.filedialog.askopenfilename()
        self.txt_path2.set(self.file2)

    def Diff(self):
        '''
        比对文件
        @return:
        '''
        with open(self.file1) as f1,open(self.file2) as f2:
            text1=f1.readlines()
       # with open(file2) as f2:
            text2=f2.readlines()
        try:
            diff=difflib.HtmlDiff()
            with open('result.html','w') as f:
                f.write(diff.make_file(text1,text2))
            tkinter.messagebox.showinfo("info","比对完毕!")
        except Exception as e:
            tkinter.messagebox.showerror("error","e")
            raise e


if __name__ == '__main__':
    Window=WINDOW()

运行效果

python学习-实现对比文件输出html_python

python学习-实现对比文件输出html_Diff_02


举报

相关推荐

0 条评论