我有一个像这样的 input_file.fa 文件( FASTA 格式):
> header1 description
data data
data
>header2 description
more data
data
data
我想一次读入文件中的一个 block ,以便每个 block 包含一个 header 和相应的数据,例如 block 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: illegal newline value: >
我也尝试过使用 csv module ,但没有成功。
我确实找到了this post从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包。
关于python - python中使用指定分隔符逐 block 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38655176/