尝试比较在 Python 2.4 中使用 'with open...' 打开的文件给出 SyntaxError

Trying to compare files opened using 'with open...' in Python 2.4 gives a SyntaxError

如何在 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 的系统调用是可能的。

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.