将 for 循环的输出保存到文件
我打开了一个包含爆炸结果的文件,并将结果以 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 呢?
I have opened a file with blast results and printed out the hits in fasta format to the screen.
The code looks like this:
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
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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,创建一个文件对象:
您可以打印到文件对象:
或者您可以写入它:
然后您可以关闭它:
First, create a file object:
You can print to a file object:
Or you can write to it:
You can then close it to be nice:
像这样的东西
不喜欢使用
print >>
因为它在 Python3 中不再起作用Something like this
prefer not to use
print >>
as that won't work anymore in Python3您可以使用
with语句
来确保文件将被关闭或使用
try ...finally
you can use
with statement
to ensure that file will be closedor use
try ... finally
有两种一般方法。在 Python 之外:
或者,在 Python 内部:
There are two general approaches. Outside of python:
Or, inside of Python:
由于某种原因,OP发布的上面的代码对我不起作用..我修改了一点
for some reason the code above posted by OP did not work for me.. I modified a bit