一、模块的功能
主要是用来进行序列的差异化比较,它能够比对文件并生成差异结果文本或者html格式的差异化比较页面!
换句话说:生成比linux中diff更人性化的文件差异比较!
二、练习
练习1:体会splitlines的作用
# difflib库的作用!
text1 = ''' 1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
'''.splitlines(keepends=True)
text2 = ''' 1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.
'''.splitlines(keepends=False)
print(text1)
print(text2
# 返回一个列表(各元素为每行的元素)
需求2:实现linux里面类似diff命令的功能
import difflib #官方的第三方模块!
text1 = ''' 1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
'''.splitlines(keepends=True)
text2 = ''' 1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.
'''.splitlines(keepends=True)
# keepends=True的含义是保留\n,(一般保留\n)
# 理解官方内置的第三方模块和内置进环境的模块!
d = difflib.Differ()
# print(list(d.compare(text1,text2)))
# 说明:由于保留空格,所以这里打印 不是连成一行
print(''.join(list(d.compare(text1, text2))))
############################################
# 说明:以html页面的形式展示差异性
d = difflib.HtmlDiff()
# 说明:html的内容
htmlContent = d.make_file(text1, text2)
# print(htmlContent)
练习2:将生成的差异性文件制作成html页面
# 保存到文件中,以浏览器打开
import difflib
filename1='/tmp/passwd'
filename2='/tmp/passwd1'
#(1)生成html页面的内容
with open(filename1) as f1,open(filename2) as f2:
content1=f1.read().splitlines(keepends=True)
content2=f2.read().splitlines(keepends=True)
d=difflib.HtmlDiff()
htmlContent=d.make_file(content1,content2)
#(2)生成html格式的文件
with open('passwdDiff.html','w') as file:
file.write(htmlContent)
# 涉及html页面的生成,以及文件的读写!