簡體   English   中英

將for循環的輸出保存到文件

[英]Saving output of a for-loop to file

我打開了一個帶有爆破結果的文件,並以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()替換循環中的print語句,但是我們如何編寫'>',alignment.title?

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

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

像這樣的東西

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中不再起作用

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

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

或者try ... finally使用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()

有兩種一般方法。 在python之外:

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

由於某種原因,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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM