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

Jon*_*Jon 3 python loops file save

我打开了一个带有爆破结果的文件,并以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
Run Code Online (Sandbox Code Playgroud)

这会将fasta文件列表输出到屏幕.但是如何创建文件并将fasta输出保存到此文件中?

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

tru*_*ppo 7

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

f = open("myfile.txt", "w") # Use "a" instead of "w" to append to file
Run Code Online (Sandbox Code Playgroud)

您可以打印到文件对象:

print >> f, '>', alignment.title
print >> f, hsp.sbjct 
Run Code Online (Sandbox Code Playgroud)

或者你可以写信给它:

f.write('> %s\n' % (alignment.title,))
f.write('%s\n' % (hsp.sbjct,))
Run Code Online (Sandbox Code Playgroud)

然后你可以把它关闭好看:

f.close()
Run Code Online (Sandbox Code Playgroud)