如何在Python 2.4.4中比较两个文件?文件的长度可以不同。
我们的服务器上有Python 2.4.4。我想使用difflib.unified_diff()
函数,但我找不到适用于Python 2.4.4的示例。
我在Stack Overflow上看到的所有版本都包含以下内容:
with open("filename1","r+") as f1:
with open ("filename2","r+") as f2:
difflib.unified_diff(..........)
我遇到的问题是版本2.4.4 with open ...
生成一个SyntaxError。我想远离使用系统调用diff或sdiff是可能的。
答案 0 :(得分:4)
with
声明为introduced in Python 2.5。不过没有它你可以直截了当地做到:
<强> A.TXT 强>
This is file 'a'.
Some lines are common,
some lines are unique,
I want a pony,
but my poetry is awful.
<强> b.txt 强>
This is file 'b'.
Some lines are common,
I want a pony,
a nice one with a swishy tail,
but my poetry is awful.
<强>的Python 强>
import sys
from difflib import unified_diff
a = 'a.txt'
b = 'b.txt'
a_list = open(a).readlines()
b_list = open(b).readlines()
for line in unified_diff(a_list, b_list, fromfile=a, tofile=b):
sys.stdout.write(line)
<强>输出强>
--- a.txt
+++ b.txt
@@ -1,6 +1,6 @@
-This is file 'a'.
+This is file 'b'.
Some lines are common,
-some lines are unique,
I want a pony,
+a nice one with a swishy tail,
but my poetry is awful.