Saving output of a for-loop to file

前端 未结 5 951
礼貌的吻别
礼貌的吻别 2020-12-17 06:32

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         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 06:59

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

提交回复
热议问题