SeqIO.parse on a fasta.gz

…衆ロ難τιáo~ 提交于 2019-12-05 01:28:09

Are you using python3?

This ("r" --> "rt") could solve your problem.

import gzip
from Bio import SeqIO

with gzip.open("practicezip.fasta.gz", "rt") as handle:
    for record in SeqIO.parse(handle, "fasta"):
        print(record.id)

Here is a solution if you want to handle both regular text and gzipped files:

import gzip
from mimetypes import guess_type
from functools import partial

from Bio import SeqIO

input_file = 'input_file.fa.gz'

encoding = guess_type(input_file)[1]  # uses file extension
if encoding is None:
    _open = open
elif encoding == 'gzip':
    _open = partial(gzip.open, mode='rt')
else:
    raise ValueError('Unknown file encoding: "{}"'.format(encoding))

with _open(input_file) as f:
    for record in SeqIO.parse(f, 'fasta'):
        print(record)

NOTE: this relies on the file having the correct file extension, which I think is reasonable nearly all of the time (and the errors are obvious and explicit if this assumption is not met). However, read here for ways to actually check the file content rather than relying on this assumption.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!