Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

python - Saving output of a for-loop to file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

Or you can write to it:

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

You can then close it to be nice:

f.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...