如何在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
热门推荐
4 狗狗请人训练
5 训练狗狗迎宾
6 训练狗狗解放
7 抬头训练狗狗
10 训练狗狗的基本动作
11 两个月狗狗怎么训练大小便
12 教狗狗训练
13 记叙文训练狗狗
14 潮州训练狗狗
15 训练狗狗叫的方法
16 猫训练狗狗
17 狗狗训练如厕
18 狗狗来训练