首页 > 解决方案 > for 循环的顺序会影响结果

问题描述

运行以下代码时。只有循环 1 将被执行,循环 2 消失了。但是,如果我将循环 1 移到循环 2 后面,则两个循环都将被执行。这是为什么 ?谢谢

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)

标签: python

解决方案


这是因为您已经在第一个循环中使用了文件句柄。一个简单的例子可能是:

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

如果你想读取一个文件两次,你可以使用fh.seek(0)回到开头:

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

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

推荐阅读