尝试比较在Python 2.4中使用'with open ...'打开的文件会产生一个SyntaxError

时间:2015-04-09 19:18:09

标签: python file with-statement python-2.4 difflib

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

1 个答案:

答案 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.