CamelopardalisRex
CamelopardalisRex

Reputation: 363

Comparing a list with a a text document

So I generate a list within my code and now I want to check it against an existing document to see what differences there are before making a new document.

Here is my attempt:

  diff = ""
    if File2_Loc :
        File2 = open( File2_Loc , 'r' )
        for line in R_List :
            if line in File2 :
                pass
            else :
                diff += ( line.strip() + " not found in old file.\n" )
        for line in File2 :
            if line == "***** Differences founds : *****\n" :
                print( "Compared!")
                break
            if line in R_List :
                pass
            else :
                diff += ( line.strip() + " not found in new file.\n" )
    else :
        print( "No file inputted:" )
    for line in R_List :
        File1.write( line )
    File1.write( "***** Differences founds : *****\n" )
    if diff :
        File1.write( diff )
    else :
        File1.write( "None.\n" )

The problem here is, every single line within R_List isn't found in File2, even though 100% of them should be.

I've looked for a solution already, but I didn't see anything that addressed my problem or worked for my problem.

Upvotes: 2

Views: 69

Answers (1)

honza_p
honza_p

Reputation: 2093

This is because the file is read only once. If you call "in" on it, it is not iterated over again (it is "read" from the current position which is the end of file). So the solution would be to read all file into memory using File2.readlines() and try "in" on that thing :-)

    File2 = open( File2_Loc , 'r' )
    lines2 = File2.readlines()  # Define the lines here
    File2.close()               # This is also a good idea
    for line in R_List :
        if line in lines2 :     # Iterate over lines instead of file
            pass
        else :
            diff += ( line.strip() + " not found in old file.\n" )
    for line in lines2 :        # Iterate over lines instead of file
        if line == "***** Differences founds : *****\n" :
            print( "Compared!")
            break
        if line in R_List :
            pass
        else :
            diff += ( line.strip() + " not found in new file.\n" )

Solution 2: This solution uses sets and operator "-" making disjunction on them:

    File2 = open( File2_Loc , 'r' )
    lines2 = File2.readlines()  # Define the lines here
    File2.close()               # This is also a good idea
    not_in_file2 = list(set(R_list) - set(lines2))
    not_in_rlist = list(set(lines2) - set(R_list))
    # Finish the diff output accordingly.

Upvotes: 2

Related Questions