在Biopython中捕获Genbank文件解析错误

时间:2012-12-07 20:15:16

标签: python biopython

我使用BioPython Entrez模块下载this post行的genbank文件列表。在随后解析这些文件时,我遇到了一个错误,因为我从Entrez下载的genbank文件是一个临时RefSeq的一部分,它给了一个基因组不完整的生物体(NZ_CM000913.1)。当我尝试读取此文件时,出现记录错误,我的脚本停止。我正在尝试编写一个可以避免这些记录的函数。最简单的方法是按大小过滤记录,但我想知道如何更多地进行生物蟒蛇的研究。 - 测试文件是否包含记录,然后排除,如果它没有。将引发当前的ValueError消息,但将停止脚本。

#the error message is something like this    
from Bio import SeqIO
gbkfile = 'NZ_CM000913.1'
SeqIO.read(open(gbkfile), 'gb')

      File "/usr/lib64/python2.6/site-packages/Bio/SeqIO/__init__.py", line 605, in read
        raise ValueError("No records found in handle")

对于我的循环,我可以使用这样的东西:

#filter by length
for gbk in gbklist:
    if len(open(gbk).readlines()) < 50:
        print 'short file: exclude'
    else:
        process_gbk(gbk)

但我想知道是否可以从BioPython中捕获错误消息:

#generate GBK-file exception    
for gbk in gbklist:
    try: 
        SeqIO.read(open(gbk),'gb')
        process_gbk(gbk)
    except BiopythonIO: 
        'this file is not a genbank file'
        pass

2 个答案:

答案 0 :(得分:2)

我可以使用Biopython打开NZ_CM000913.1,实际上是:

>>> from Bio import SeqIO
>>> fname = 'NZ_CM000913.1.gbk'
>>> recs = SeqIO.read(fname, 'genbank')
>>> recs
SeqRecord(seq=UnknownSeq(6760392, alphabet = IUPACAmbiguousDNA(), character = 'N'), id='NZ_CM000913.1', name='NZ_CM000913', description='Streptomyces clavuligerus ATCC 27064 chromosome, whole genome shotgun sequence.', dbxrefs=['Project:47867 BioProject:PRJNA47867'])

您确定已正确下载文件而非空文件吗?

另外,我注意到您正在向open('NZ_CM000913.1.gbk')提供SeqIO.read。只需提供文件名(SeqIO.read('NZ_CM000913.1.gbk', 'genbank'))以防止文件句柄未闭合,这样会更好(也更容易阅读)。

答案 1 :(得分:2)

你的建议几乎就在那里!这是完成它+一些方便的津贴(阅读评论)

errorList = []                               # to store your erroneous files for later handling ;)

#generate GBK-file exception 
for gbk in gbklist:
    try: 
        SeqIO.read(open(gbk),'gb')
        process_gbk(gbk)
    except ValueError:                       # handles your ValueError
        print(gbk+' is not a genbank file')  # lets you know the file causing the error "live"
        errorList.append(gbk)                # logs the name of erroneous files in "errorList"
        continue                             # skips straight to the next loop