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

3

我已经用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将如何被写入?
5个回答

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

所有在打开文件后的操作都应该被包裹在 try ... finally 中,以确保文件能够正确关闭。 - Victor Kotseruba
在长时间运行的进程中,是的,在简单的脚本中并不重要,因为文件将在脚本退出时关闭。 - mthurlin

4

Something like this

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中已经无法使用了。


4
您可以使用with语句确保文件会被关闭。
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()

2

有两种常见的方法。在Python之外:

python your_program.py >output_file.txt

或者,在Python内部:

out = open("output_file.txt", "w")
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        print >>out, '>', alignment.title
        print >>out, hsp.sbjct
out.close()

0

由于一些原因,OP发布的上面的代码对我来说不起作用...我进行了一些修改

from Bio.Blast import NCBIXML
f = open('result.txt','w')
for record in NCBIXML.parse(open("file.xml")) :
    for alignment in record.alignments:
        for hsp in alignment.hsps:
            f.write(">%s\n"%alignment.title)
            f.write(hsp.sbjct+"\n")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接