views:

346

answers:

4

Hi,

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?

Thanks! Jon

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?

+1  A: 

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()
truppo
all operations after opening file should be wrapped with try ... finally to ensure that file will be correctly closed
barbuza
In a long running process, yes, in a simple script it doesnt matter as files will be closed when script exits.
truppo
+2  A: 

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()
Greg Hewgill
+1  A: 

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

gnibbler
+2  A: 

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