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


问题内容

我有一个这样的input_file.fa文件(FASTA格式):

> header1 description
data data
data
>header2 description
more data
data
data

我想一次在文件中读取一个块,以便每个块包含一个标头和相应的数据,例如块1:

> header1 description
data data
data

当然,我可以像这样读取文件并拆分:

with open("1.fa") as f:
    for block in f.read().split(">"):
        pass

但是 我要避免将整个文件读入内存 ,因为文件通常很大。

我当然可以逐行读取文件:

with open("input_file.fa") as f:
    for line in f:
        pass

但理想情况下,我想要的是这样的东西:

with open("input_file.fa", newline=">") as f:
    for block in f:
        pass

但我得到一个错误:

ValueError:非法换行值:>

我也尝试过使用csv模块,但没有成功。

我确实在3年前找到了这篇文章,它提供了基于发电机的解决方案,但似乎并不紧凑,这真的是唯一/最佳的解决方案吗?如果可以用单行而不是单独的函数来创建生成器,就像下面的伪代码一样,那就太好了:

with open("input_file.fa") as f:
    blocks = magic_generator_split_by_>
    for block in blocks:
        pass

如果这不可能,那么我想您可以考虑我的问题与其他帖子的重复,但是如果是这样,我希望人们可以向我解释为什么其他解决方案是唯一的解决方案。非常感谢。


问题答案:

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

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软件包。