I can’t see the problem here and it is driving me insane. I’m looping through 2 text files. Some lines in each file match and some don’t. What I am doing is looping over file1. For each line in that file, loop over file2 and compare each element to see if they are the same. What’s happening is my loop is stopping after the first loop through file1. Here is my code:
while f < 50:
for line in file1:
for name in file2:
if name == line:
print 'a match was found'
f+=1
The while loop comes from somewhere else but it is working fine. I just included it for context. The problem is file1 only gives me the first line, compares it to all of the ‘names’ in file2 then stops instead of repeating the process for the next line in file1. Am I missing something glaringly obvious?
EDIT: If I put a print statement in after the first for loop and comment out the other for loop it loops through the whole first file
You cannot loop through a file and then loop through the same file again without seeking to the start.
Either re-open file2, call
.seek(0)on file2 or load all lines into a list and loop over that instead.In your specific case, using a
setfor the names is probably going to be the fastest:You can do the same with the lines in file1 and do a set intersection, provided that lines are unique in both file1 and file2.