【发布时间】:2021-03-11 15:55:45
【问题描述】:
我使用 for 循环读取多个文件,并使用以下代码将输出附加到单独的文件中。我正在寻找的不是每次迭代都打印count+=1 之后的行(请参见下文),除了最后一次迭代。
output.write(file_name + ": The total number of reads with two AB sequences is " +
str(count) + '\n')
有没有办法根据我的代码在输出文件的末尾只打印一次最终的count+=1?
from Bio import SeqIO
files=['2_.fasta','4_.fasta']
for file_name in files:
count=0
with open(file_name,'r') as f:
for record in SeqIO.parse(f,'fasta'):
#some code
if str(v1) in record.seq and str(v2) in record.seq:
#some code
out = "sample" + file_name[:1] + "_two_AB.txt"
with open(out,'a') as output:
output.write(file_name + '\n')
output.write(">"+str(record.id) + '\n')
count+=1
output.write(file_name + ": The total number of reads with two AB sequences is "
+ str(count) + '\n')
output.close()
【问题讨论】:
-
如果我理解了您的问题,您可以使用列表来保存文件名、计数和record.id。在 FOR 之后,您使用列表将数据写入另一个 FOR。
-
每次
open(out,'w') as output文件中可能已经存在的任何内容都会丢失(覆盖)。 -
感谢 m@martineau 的提醒,我实际上使用
append模式 - 忘记在这个问题中更新它。 -
@Ferdinando,你能帮我看看你建议的一段代码吗?
-
@Apex,如果您需要其他内容,请写信给我并更新我的答案。