将for循环的输出保存到文件 [英] Saving output of a for-loop to file

查看:692
本文介绍了将for循环的输出保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开了一个具有爆炸结果的文件,并以fasta格式将匹配结果打印到屏幕上.

I have opened a file with blast results and printed out the hits in fasta format to the screen.

代码如下:

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输出保存到该文件中?

This outputs a list of fasta files to the screen. But how can I create a file and save the fasta output to this file?

更新:我想我将不得不用something.write()替换循环中的打印语句,但是我们写的'>',alignment.title将如何?

Update: I guess I would have to replace the print statements within the loop with something.write(), but how will the '>', alignment.title we written?

推荐答案

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

First, create a file object:

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

您可以打印到文件对象:

You can print to a file object:

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

或者您可以写信给它

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

然后可以将其关闭以保持良好状态:

You can then close it to be nice:

f.close()

这篇关于将for循环的输出保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆