如何在Python中查找两个文件之间的差异?
Python标准库具有专门用于查找字符串/文件之间差异的模块。使用difflib库获取差异,您可以简单地在其上调用united_diff函数。
阅读更多:Python 教程
例子
例如,假设您有两个文件file1和file2,其内容如下:
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()
# 查找并打印差异:
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
极客教程