Saving output of a for-loop to file

18,979

Solution 1

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\n' % (alignment.title,))
f.write('%s\n' % (hsp.sbjct,))

You can then close it to be nice:

f.close()

Solution 2

Something like this

with open("thefile.txt","w") as f
  for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
      f.write(">%s\n"%alignment.title)
      f.write(hsp.sbjct+"\n")

prefer not to use print >> as that won't work anymore in Python3

Solution 3

you can use with statement to ensure that file will be closed

from __future__ import with_statement

with open('/Users/jonbra/Desktop/my_blast.xml', 'w') as outfile:
    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:
            outfile.write('>%s\n%s\n' % (alignment.title, hsp.sbjct))

or use try ... finally

outfile = open('/Users/jonbra/Desktop/my_blast.xml', 'w')
try:
    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:
            outfile.write('>%s\n%s\n' % (alignment.title, hsp.sbjct))
finally:
    outfile.close()

Solution 4

There are two general approaches. Outside of python:

python your_program.py >output_file.txt

Or, inside of Python:

out = open("output_file.txt", "w")
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        print >>out, '>', alignment.title
        print >>out, hsp.sbjct
out.close()
Share:
18,979
Jon
Author by

Jon

Evolutionary biologist.

Updated on June 07, 2022

Comments

  • Jon
    Jon almost 2 years

    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?