user11200132
user11200132

Reputation:

The order of the for loops affect the outcome

When running the following codes. Only loop 1 will be executed the loop 2 is gone. However if i move loop 1 behind loop2, both of the loops will be executed. Why is that ? Thank you

from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML

with open('input.txt', 'r') as file:

    count = 1

    #loop 1
    for i in file:
        print("Sequence {} :{}  Length: {}".format(count, i[:20], len(i)))
        count += 1
    count -= 1
    print("There are %d sequences." % count)  # count = 10

    #loop2
    for i in range(count):
        seq = file.readline()
        print(seq)
        # try:
        #     with open('dna_lab5_%d.xml' % i, 'r') as f:
        #         print("Using saved file")
        # except FileNotFoundError:
        #     print("Performing online BLAST search")
        #     with open('dna_lab5_%d.xml' % i, 'w') as f:
        #         print(seq)
        #         # handle = NCBIWWW.qblast("blastn", "nt", seq)
        #         # result = handle.read()
        #         # f.write(result)

Upvotes: 0

Views: 59

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

It's because you've consumed the file handle already in the first loop. A simple example might be:

with open('afile.txt') as fh:
    # this will consume fh
    for line in fh:
        print(line)

    print(fh.readline()) # prints empty string, because there's nothing left to read

    for line in fh:
        print(line) # won't do anything because you've already read everything

If you want to read a file twice, you can use fh.seek(0) to go back to the beginning:

with open('afile.txt') as fh:
    for line in fh:
        print(line)

    fh.seek(0)
    # now this works
    for line in fh:
        print(line)

Upvotes: 2

Related Questions