Saving output of a for-loop to file

前端 未结 5 938
礼貌的吻别
礼貌的吻别 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:32

    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()
    
    0 讨论(0)
  • 2020-12-17 06:33

    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

    0 讨论(0)
  • 2020-12-17 06:35

    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")
    
    0 讨论(0)
  • 2020-12-17 06:50

    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()
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题