python写的文件比对脚本:
上代码:
# -*- coding: utf-8 -*-
import difflib,webbrowser
import os
import tkinter as tk
from tkinter import filedialog,messagebox
def readfile(filename):
try:
with open(filename,'r+',encoding='utf-8') as f:
text=f.read().splitlines() #结果为每行的列表
return text
except IOError as error:
messagebox.showerror('警告',filename+'读取失败'+str(error))
def savediff(file1,file2):
lines1=readfile(file1)
lines2=readfile(file2)
d=difflib.HtmlDiff()
with open(htmlfile,'w',encoding='UTF-8') as f:
res=d.make_file(lines1,lines2)
f.write(res)
def getfile(filepath):
dirs=os.path.dirname(os.path.abspath(__file__))
path=filedialog.askopenfilename(title=u'选择文件',initialdir=dirs)
filepath.set(path)
def compare():
file1=path1.get()
file2=path2.get()
savediff(file1,file2)
webbrowser.open(htmlfile) #打开html
if __name__=='__main__':
window = tk.Tk()
window.title('文件比对小工具')
window.geometry('500x400') # 这里的乘是小x
window.wm_attributes('-topmost',True)
path1=tk.StringVar()
path2=tk.StringVar()
htmlfile='比对结果.html'
tk.Button(window,text='打开文件一',command=lambda:getfile(path1)).grid(row=0,column=0,pady=2)
tk.Entry(window,textvariable=path1,width=40).grid(row=0,column=1)
tk.Button(window,text='打开文件二',command=lambda:getfile(path2)).grid(row=1,column=0,pady=2)
tk.Entry(window,textvariable=path2,width=40).grid(row=1,column=1)
tk.Button(window,text="执行文件比对",command=compare).grid(row=2,column=0,pady=5)
window.mainloop()
实现效果如下:
然后选择文件路径,执行文件比对,会跳出来网页显示两者文件间的区别