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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 8
    Please upgrade from 2.4.4. If you're about to say "that's up to the server host", please hire new server hosts. If you're about to say "my employer likes it this way", please seek new employment. – Kevin Apr 09 '15 at 19:23
  • 2.4.4 is really old ... that said you can do `f1,f2 = open("fname1.txt"),open("fname2.txt")` – Joran Beasley Apr 09 '15 at 19:24

1 Answers1

4

The with statement was introduced in Python 2.5. It's straightforward to do what you want without it, though:

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)

Output

--- 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.
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • Worked like a charm. I actually messed around with the other difflib options and the format that you provided and found that the following gave a better output: for line in context_diff(a_list, b_list, fromfile=a, tofile=b): – Michael Duff Apr 10 '15 at 15:45