2009-11-05 179 views
3

我已經開始與爆炸結果的文件和打印出來FASTA格式的點擊屏幕。保存輸出到文件

的代碼看起來是這樣的:

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 

這種輸出的FASTA文件在屏幕上的列表。 但我怎樣才能創建一個文件並保存fasta輸出到這個文件?

更新:我想我將不得不更換something.write()循環內的打印報表,但如何將「>」,alignment.title我們寫的?

回答

7

首先,創建一個文件對象:

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

可以打印到文件對象:

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

或者你可以寫入:

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

然後,您可以關閉它是好的:

f.close() 
+0

所有操作包裹着試試......終於,以確保文件將被正確關閉 – barbuza

+0

在一個長期運行的進程,是的,在一個簡單的腳本它不事關爲腳本退出時的文件將被關閉。 – truppo

2

一般有兩種方法。蟒蛇之外:

python your_program.py >output_file.txt 

或者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() 
4

像這樣的事情

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

可以使用with statement,確保文件將被關閉

​​

或使用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

出於某種原因上面貼由OP代碼並沒有爲我工作。我修改了一下打開文件後應

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