Saving output of a for-loop to file(将 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
' % (alignment.title,))
f.write('%s
' % (hsp.sbjct,))
然后你就可以关闭它了:
You can then close it to be nice:
f.close()
这篇关于将 for 循环的输出保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 for 循环的输出保存到文件
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
