如何在Python中逐行比较两个不同的文件?
Python标准库具有专门用于查找字符串/文件之间差异的模块。要使用difflib库获取diff,只需在其上调用united_diff函数即可。例如,假设您有两个文件,文件1和文件2具有以下内容-
file1: Hello People of the world file2: Hello People from India
示例
现在使用下面的代码来比较它们-
import difflib
with open('file1') as f1:
f1_text = f1.read()
with open('file2') as f2:
f2_text = f2.read()
# Find and print the diff:
for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''):
print line输出结果
这将给出输出-
--- file1 +++ file2 @@ -1,5 +1,4 @@ Hello People -of -the -world +from +India
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语