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

时间:2009-11-05 22:45:49

标签: python file loops save

我打开了一个带有爆破结果的文件,并以快拍格式打印到屏幕上。

代码如下所示:

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 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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中不再起作用

答案 2 :(得分: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()

答案 3 :(得分: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()

答案 4 :(得分: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")