将for循环的输出保存到fi

2024-09-28 21:00:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我打开了一个包含blast结果的文件,并以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输出保存到这个文件中呢?

更新:我想我必须用something.write()替换循环中的print语句,但是我们编写的'>;'alignment.title将如何替换?


Tags: 文件infor屏幕titleresultrecordfasta
3条回答

您可以使用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()

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

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()

像这样的东西

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中不再有效

相关问题 更多 >