![](/img/trans.png)
[英]Separate headers from sequences in fasta file without using Biopython
[英]save sequences from NCBI in fasta format using a list of IDs in excel
我是使用python的新手,我喜歡它。 但是,我一直困擾着這個問題,希望您能給我一個關於我所缺少的東西的信息。
我在excel文件中有一個基因ID列表,我正在嘗試使用xrld和biopython檢索序列並將結果保存(以fasta格式)到文本文檔中。 到目前為止,我的代碼允許我在shell中查看結果,但它僅將最后一個序列保存在文檔中。
這是我的代碼:
import xlrd
import re
book = xlrd.open_workbook('ids.xls')
sh = book.sheet_by_index(0)
for rx in range(sh.nrows):
if sh.row(rx)[0].value:
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "mail@xxx.com"
in_handle = Entrez.efetch(db="nucleotide", rettype="fasta", id=sh.row(rx)[0].value)
record = SeqIO.parse(in_handle, "fasta")
for record in SeqIO.parse(in_handle, "fasta"):
print record.format("fasta")
out_handle = open("example.txt", "w")
SeqIO.write(record, out_handle, "fasta")
in_handle.close()
out_handle.close()
如前所述,文件“ example.txt”僅具有顯示外殼程序的最后一個序列(以fasta格式)。
誰能幫我在同一文檔中獲取從NCBI檢索到的序列嗎?
非常感謝你
安東尼奧
我對python還是很陌生,也喜歡它! 這是我第一次嘗試回答問題,但這可能是由於您的循環結構和“ w”模式引起的嗎? 也許嘗試如下更改(“ example.txt”,“ w”)以追加模式(“ example.txt”,“ a”)?
import xlrd
import re
book = xlrd.open_workbook('ids.xls')
sh = book.sheet_by_index(0)
for rx in range(sh.nrows):
if sh.row(rx)[0].value:
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "mail@xxx.com"
in_handle = Entrez.efetch(db="nucleotide", rettype="fasta", id=sh.row(rx)[0].value)
record = SeqIO.parse(in_handle, "fasta")
for record in SeqIO.parse(in_handle, "fasta"):
print record.format("fasta")
out_handle = open("example.txt", "a")
SeqIO.write(record, out_handle, "fasta")
in_handle.close()
out_handle.close()
我的朋友們幾乎在那里!
主要問題是您的For循環會在每個循環中不斷關閉文件。 我還修復了一些小問題,這些問題應該可以加快代碼的速度(例如,您一直在每個循環中導入Bio)。
使用以下新代碼:
out_handle = open("example.txt", "w")
import xlrd
import re
from Bio import Entrez
from Bio import SeqIO
book = xlrd.open_workbook('ids.xls')
sh = book.sheet_by_index(0)
for rx in range(sh.nrows):
if sh.row(rx)[0].value:
Entrez.email = "mail@xxx.com"
in_handle = Entrez.efetch(db="nucleotide", rettype="fasta", id=rx)
record = SeqIO.parse(in_handle, "fasta")
SeqIO.write(record, out_handle, "fasta")
in_handle.close()
out_handle.close()
如果仍然出錯,則說明您的excel文件中一定有問題。 如果錯誤仍然存在,請發送給我,我會幫助您:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.