0

How can I compare two files in Python 2.4.4? The files could be different lengths.

We have Python 2.4.4 on our servers. I would like to use the difflib.unified_diff() function but I can't find examples that work with Python 2.4.4.

All the versions that I have seen on Stack Overflow contain the following:

with open("filename1","r+") as f1:
  with open ("filename2","r+") as f2:
    difflib.unified_diff(..........)

The problem that I have is within version 2.4.4 the with open ... generates a SyntaxError. I would like to stay away from using the system call to diff or sdiff is possible.

4

1 回答 1

4

with语句是在 Python 2.5 中引入的。但是,没有它就可以直接做你想做的事:

一个.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.
于 2015-04-09T19:41:49.743 回答