Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 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 Answer

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...