0

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
3
  • Is it your intention to break the inner loop just after finding the first occurence of acc in f2? Commented Oct 31, 2016 at 14:13
  • You would need to reset the file object's position, e.g.: using file.seek. Or just read the entire file into a list first and then use that in the iteration. Commented Oct 31, 2016 at 14:14
  • 2
    This code can not be tested and does not provide enough information to debug. Please at least add the code that assigns f and f2. Also, some sample inputs would be nice. Just enough to demonstrate the problem. Commented Oct 31, 2016 at 14:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, opening a file before second loop seems to work, I've tested it on small instances, now I will try on bigger one
0

Something like that might work.

f1 = 'filename1.txt'
f2 = 'filename2.txt'
with open(f1, 'r') as first_f, open(f2, 'r') as second_f:
     list_of_accs = (line[:9] for line in first_f.readlines())
     f2_lines = f2.readlines()
     for acc in list_of_accs:
         for idx, line in enumerate(f2_lines, 1):
             if acc in line:
                print('Occurence found at line {idx} with no {acc}'.format(idx=idx, acc=acc))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.