Search code examples
pythonfilefor-loopnested-loopsenumerate

Python: How to do nested enumerate for loop?


I have two files, file1 and file2, and for every file1 line, I’m trying to check against all the lines of file2.

So I did a nested enumerate for loop, but checking the first line of file1 against all the lines of file2, the program just completes, rather than moving onto the next file1 line to check against all the lines of file2.

Here is what I have:

def testing():
    file1 = open(‘file1.txt’, 'r')
    file2 = open(‘file2.txt’, 'r')

    for index1, line1 in enumerate(file1):
        for index2, line2 in enumerate(file2):
                #              Here it prints the first line of `file1.txt` and after checking against all the lines of `file2.txt` (`for index2, line2 in enumerate(file2.txt)`) it completes, rather then going to the outer loop and proceed looping
                print("THIS IS OUTER FOR LOOP LINE: " + line1 + " WITH LINE NUMBER: " + str(index1))

    file1.close()
    file2.close()

How can I check every line of file1 against all the lines of file2? What could I be doing wrong here?

Thank you in advance and will be sure to upvote/accept answer


Solution

  • Push the position of file2 back to the start at the top of each loop. Either close and reopen it as aryamccarthy suggested, or do it the cleaner way by simply moving the pointer:

    file1 = open(‘file1.txt’, 'r')
    file2 = open(‘file2.txt’, 'r')
    
    for index1, line1 in enumerate(file1):
        file2.seek(0)  # Return to start of file
        for index2, line2 in enumerate(file2):