将for循环的输出保存到文件中

3 投票
5 回答
19415 浏览
提问于 2025-04-15 15:42

我打开了一个包含比对结果的文件,并把结果以fasta格式打印到了屏幕上。

代码大概是这样的:

result_handle = open("/Users/jonbra/Desktop/my_blast.xml")

from Bio.Blast import NCBIXML
blast_records = NCBIXML.parse(result_handle)
blast_record = blast_records.next()
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        print '>', alignment.title
        print hsp.sbjct

这段代码会把fasta文件的列表显示在屏幕上。可是,我该怎么做才能把这些fasta输出保存到一个文件里呢?

更新:我想我需要把循环中的打印语句换成某种写入文件的方式,但像'>'和alignment.title这些该怎么处理呢?

5 个回答

4

你可以使用 with statement 来确保文件会被关闭。

from __future__ import with_statement

with open('/Users/jonbra/Desktop/my_blast.xml', 'w') as outfile:
    from Bio.Blast import NCBIXML
    blast_records = NCBIXML.parse(result_handle)
    blast_record = blast_records.next()
    for alignment in blast_record.alignments:
        for hsp in alignment.hsps:
            outfile.write('>%s\n%s\n' % (alignment.title, hsp.sbjct))

或者可以使用 try ... finally

outfile = open('/Users/jonbra/Desktop/my_blast.xml', 'w')
try:
    from Bio.Blast import NCBIXML
    blast_records = NCBIXML.parse(result_handle)
    blast_record = blast_records.next()
    for alignment in blast_record.alignments:
        for hsp in alignment.hsps:
            outfile.write('>%s\n%s\n' % (alignment.title, hsp.sbjct))
finally:
    outfile.close()
4

像这样

with open("thefile.txt","w") as f
  for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
      f.write(">%s\n"%alignment.title)
      f.write(hsp.sbjct+"\n")

不太想用 print >>,因为在Python3里这样用已经不行了

7

首先,创建一个文件对象:

f = open("myfile.txt", "w") # Use "a" instead of "w" to append to file

你可以把内容打印到这个文件对象里:

print >> f, '>', alignment.title
print >> f, hsp.sbjct 

或者你也可以直接写入内容:

f.write('> %s\n' % (alignment.title,))
f.write('%s\n' % (hsp.sbjct,))

最后,你可以把它关闭,这样做是为了保持整洁:

f.close()

撰写回答