1、文件差异对比代码:
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=False) 按行分割,不保留空格,生成列表
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) 按行分割,保留空格,生成列表
d = difflib.Differ()
print(''.join(d.compare(text1,text2)))
执行结果:
- 1. Beautiful is better than ugly.+ 1. Beautiful is better than ugly.
? +
- 2. Explicit is better than implicit.- 3. Simple is better than complex.? -
+ 3.Simple is better than complex.
? +
- 4. Complex is better than complicated.? ^ ---- ^
+ 4. Complicated is better than complex.
? ++++ ^
Python difflib模块实现文件差异对比

本文介绍了如何使用Python的difflib模块进行文件差异对比,包括代码示例和生成HTML展示差异,以及在Linux环境下进行文件内容对比的方法。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



