Asia Asia - 1 month ago 7
Python Question

Python loop for

I have a loop problem - I have to read files ('f' and 'f2') and I am trying to get each line from 'f' with accession number ('acc') and find lines containing this 'acc' in file 'f2'. The loop with 'f2' is not working properly. After finding 'acc' in 'f2' it should move to next line in 'f' and start searching for 'acc' from first line2 in 'f2' but it doesn't, it seems like it starts from where it ends, are there any simple solutions to that?

f = open("test1.txt", "r")
f2 = open("test2.txt", "r")

for line in f:
acc = line[0:9]
for line2 in f2:
if acc in line2:
print line2
break

Answer

You don't show how you are defining f or, more importantly, f2, but if f2 is an open file, then you need to either open it just before your loop to read from it (so it starts at the beginning) or at least reset the file pointer (using seek) to go back to the beginning.