Saving output for loop to file

I opened the file with the explosion results and printed the hits in fasta format on the screen.

The code is as follows:

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 displays a list of fasta files. But how can I create a file and save the fasta output to this file?

Update: I think I would have to replace the print statements in the something.write () loop, but how will '>', alignment.title be written?

+3
source share
5 answers

First create an object file:

f = open("myfile.txt", "w") # Use "a" instead of "w" to append to file

You can print the file file:

print >> f, '>', alignment.title
print >> f, hsp.sbjct 

Or you can write him:

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

Then you can close it to be nice:

f.close()
+7
source

Something like that

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

print >>, Python3

+4

you can use with statementto ensure that the file is 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()
+4
source

There are two general approaches. Outside of python:

python your_program.py >output_file.txt

Or inside 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()
+2
source

for some reason the code above sent by OP did not work for me .. I changed a little

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")
0
source

Source: https://habr.com/ru/post/1722056/


All Articles