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(\"/Use
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()
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
for some reason the code above posted by OP did not work for me.. I modified a bit
from Bio.Blast import NCBIXML
f = open('result.txt','w')
for record in NCBIXML.parse(open("file.xml")) :
for alignment in record.alignments:
for hsp in alignment.hsps:
f.write(">%s\n"%alignment.title)
f.write(hsp.sbjct+"\n")
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()
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()