python - 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)
解决方案
这是因为您已经在第一个循环中使用了文件句柄。一个简单的例子可能是:
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)
推荐阅读
- angular - 如何确保始终了解第三方 API 的最新 API 速率限制?
- javascript - 无法单击 ReactJS Hooks 中的按钮?
- sql - 如何使用分区并保持一致性
- git - 如何在某个目录上“git diff-tree”?
- android - 如果视图未滚动,则不会在适配器中获取单击事件
- android - 如何在 aar 库中使用 android room?
- amazon-web-services - AWS ALB 502 错误网关
- angular - 从另一个具有属性的对象中找到一个对象
- jquery - 使用 laravel / ajax 显示依赖选择框的值
- node.js - Node.js 子进程在第二次调用后未启动