How to use cmp() function to compare 2 files?

yinglcs at gmail.com yinglcs at gmail.com
Tue Feb 27 00:12:21 EST 2007


On Feb 26, 10:53 pm, "ying... at gmail.com" <ying... at gmail.com> wrote:
> On Feb 26, 10:22 pm, "Dan Bishop" <danb... at yahoo.com> wrote:
>
>
>
> > On Feb 26, 10:09 pm, "ying... at gmail.com" <ying... at gmail.com> wrote:
>
> > > Hi,
>
> > > i have 2 files which are different (1 line difference):
> > > $ diff groupresult20070226190027.xml groupresult20070226190027-2.xml
> > > 5c5
> > > < x:22 y:516 w:740 h:120 area:
> > > ---
>
> > > > x:22 y:516 w:740 h:1202 area:
>
> > > But when I use the cmp() function to compare 2 files, it return "1",
>
> > > $ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47)
> > > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
> > > Type "help", "copyright", "credits" or "license" for more information.>>> cmp("groupresult20070226190027.xml", "groupresult20070226190027-2.xml")
>
> > > 1
>
> > > Can you please tell me why?
>
> > Because '.' > '-' (character 25 of each string).
>
> > But this is comparing the filenames, which isn't what you want to do.
>
> > > And how can I compare the content of 2
> > > files in python?
>
> > Use the difflib module.
>

I try this:
  f1 = open("f1",'r')
        f2 = open("f2", 'r')


        if (difflib.context_diff(f1.readlines(), f2.readlines()).len()
== 0):

But I get this error:
Traceback (most recent call last):
  File "./scripts/regressionTest.py", line 72, in ?
    runTest(savedPagesDirectory, outputDir, expectedResultDir,
failedDir);
  File "./scripts/regressionTest.py", line 60, in runTest
    getSnapShot(fileName, testNo, outputDir, expectedResultDir,
failedDir)
  File "./scripts/regressionTest.py", line 30, in getSnapShot
    if (difflib.context_diff(f1.readlines(), f2.readlines()).len() ==
0):
         # no difference
    else:
         # files are different
AttributeError: 'generator' object has no attribute 'len'

Can you please help?




More information about the Python-list mailing list