python路径分隔符_使用python中指定的分隔符逐块读取文件 - 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 module,但没有成功。

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

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 sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…从Azure Data Factory执行python脚本 - python

有人可以帮我从Azure数据工厂执行python函数吗?我已经将python函数存储在blob中,并且我试图触发同样的功能。但是我无法做到这一点。请协助。第二,我可以从ADF参数化python函数调用吗? python参考方案 您可能会发现ADF中的Azure Function Activity概念,它允许您在Data Factory管道中运行Azure F…Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值