Neon Flash
Neon Flash

Reputation: 3233

Comparing Files recursively in Python

I have a code written in Python. It generates two files based on a variable 'i'. Now, I need to compare one of these two generated files with a keyfile to get the correct value of 'i'.

I am using a FOR loop to test a range of values of 'i' and using filecmp.cmp to compare one of the generated files with a keyfile. Moment I find a match, that means I have the correct value of 'i'.

Here is a section of the code:

for i in range(100,0,-1):

....

    with open("file1", "w") as p, open("file2", "w") as q:
        # generate data based on the value of i and write it to the files

    if(filecmp.cmp("file1", "keyfile"))
            print "%d is the correct value of it" % i
            break

should work this way:

  1. test the values of 'i' from 100 to 0 decrementing 'i' one by one.
  2. file1 and file2 are generated using a code that is based on the value of 'i'.
  3. now, I am comparing file1 with the keyfile. If they have the same contents, I found the correct key and I break the FOR loop.

I have put the filecmp.cmp statement in the if statement as it returns a boolean value True if the two files are equal. This line throws an error when I run the code though.

Also, is this the correct way of doing it? Each time the FOR loop is executed, it will generate two files, file1 and file2. With statement will close these 2 files after the loop. But in the next run of the loop will these two files be overwritten with new content?

Thanks.

Upvotes: 0

Views: 210

Answers (2)

tobias_k
tobias_k

Reputation: 82899

If this is your actual code (or parts of it), when the error you are getting in the if line is probably a SyntaxError due to a missing colon (:) at the end of the line.

Also, I would recommend not writing to actual files and then using filecmp to compare those files, but to read your keyfile into a string variable, writing your file1 into another string variable, and then comparing those variables. Once you have found the right value for i you can write the actual files file1 and file2, instead of writing (and overwriting) them up to a hundred times.

Pseudocode:

with open("keyfile") as k:
    keyfile = k.read()
    for i in range(100, 0, -1):
        file1 = # generate data based on the value of i
        if keyfile == file1:
            file2 = # generate data based on the value of i
            with open("file1", "w") as p, open("file2", "w") as q:
                # write file1 and file2 to actual files
            print "%d is the correct value of it" % i
            break

Upvotes: 1

lk_vc
lk_vc

Reputation: 1172

For your second question: with statement would close 2 files before if (filecmp ... line, and then "file1" will be reopened by filecmp; in the next run of loop, "file1" and "file2" will be overritten.

BTW. you may need to use "wb" instead of "w" in open().

Upvotes: 0

Related Questions