您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用python中指定的分隔符逐块读取文件

使用python中指定的分隔符逐块读取文件

此处的一般解决方案是为此编写一个生成函数,该函数一次生成一组。这是您一次只能在内存中存储一??组。

def get_groups(seq, group_by):
    data = []
    for line in seq:
        # Here the `startswith()` logic can be replaced with other
        # condition(s) depending on the requirement.
        if line.startswith(group_by):
            if data:
                yield data
                data = []
        data.append(line)

    if data:
        yield data

with open('input.txt') as f:
    for i, group in enumerate(get_groups(f, ">"), start=1):
        print ("Group #{}".format(i))
        print ("".join(group))

Group #1
> header1 description
data data
data

Group #2
>header2 description
more data
data
data

对于一般的FASTA格式,我建议使用Biopython软件包。

python 2022/1/1 18:42:20 有262人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶