一、文件内容差异对比方法:使用difflib自带模块,无需安装
#!/usr/bin/env python
import difflib
test1 = """ my name is Guo Hdong"""
test1_lines = test1.splitlines() #以行进行分割
test2 = """my name is Guo Yanmei"""
test2_lines = test2.splitlines()
d = difflib.Differ()
diff = d.compare(test1_lines,test2_lines)
print(‘\n‘.join(list(diff)))
执行结果
输出结果符号含义
========================================================================
升级版:输出为html格式
vim diff.py
#!/usr/bin/env python
import difflib
test1 = """ my name is Guo Hdong"""
test1_lines = test1.splitlines() #以行进行分割
test2 = """my name is Guo Yanmei"""
test2_lines = test2.splitlines()
d = difflib.HtmlDiff()
print(d.make_file(test1_lines,test2_lines))
执行脚本并输出html文件
python diff.py > test.html
==========================================================================================================
对比俩个文件的python脚本
vim diff.py
#!/usr/bin/env python
import sys
import difflib
try:
textfile1 = sys.argv[1]
textfile2 = sys.argv[2]
except Exception as e:
print("ERROR:" + str(e))
print("usage: diff.py filename1 filename2")
sys.exit()
def readfile(filename):
try:
fileHandle = open(filename,‘r‘)
text = fileHandle.read().splitlines()
fileHandle.close()
return text
except IOError as error:
print(‘Read file Error:‘ + str(error))
sys.exit()
if textfile1 == "" or textfile2 == "":
print("usage: diff.py filename1 filename2")
sys.exit()
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
运行方法:
python diff.py filename1 filename2 > aaa.html
举例
原文:https://www.cnblogs.com/python-cat/p/11096775.html