如何在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