python - 在开始和停止标志之间读取多个文件 block

标签 python

我正在尝试将文件的各个部分读入 numpy 数组,这些数组对文件的不同部分具有相似的开始和停止标志。目前我找到了一种有效的方法,但在需要重新打开输入文件之前只针对输入文件的一部分。

我现在的代码是:

    with open("myFile.txt") as f:
        array = []
        parsing = False
        for line in f:
            if line.startswith('stop flag'):
            parsing = False
        if parsing:
            #do things to the data
        if line.startswith('start flag'):
            parsing = True

我从这个 question 中找到了代码

使用此代码,我需要重新打开并通读文件。

有没有一种方法可以读取所有部分而不必为每个要读取的部分打开文件?

最佳答案

您可以在每次到达开始标志时使用 itertools.takewhile 直到停止:

from itertools import takewhile
with open("myFile.txt") as f:
        array = []
        for line in f:
            if line.startswith('start flag'):               
                data = takewhile(lambda x: not x.startswith("stop flag"),f)
                # use data and repeat

或者只使用一个内循环:

with open("myFile.txt") as f:
    array = []
    for line in f:
        if line.startswith('start flag'):
            # beginning of section use first lin
            for line in f:
                # check for end of section breaking if we find the stop lone
                if line.startswith("stop flag"):
                    break
                 # else process lines from section

文件对象返回它自己的迭代器,因此指针将在您遍历 f 时继续移动,当您到达开始标志时,开始处理一个部分,直到您停止。根本没有理由重新打开文件,只需在文件的行上迭代一次时使用这些部分。如果开始和停止标志线被认为是该部分的一部分,请确保也使用它们。

关于python - 在开始和停止标志之间读取多个文件 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507045/

相关文章:

python - * : 'NoneType' and 'int' in Python 3 不支持的操作数类型

python - 将 "global imports"注入(inject) Python 函数

python - 如何使用Python在BeautifulSoup中提取同一div中具有相同标签的元素?

python - 想要生成 databricks 笔记本 URL 来发送警报

python - Jupyter笔记本: let a user inputs a drawing

python - 推荐使用 django 的扭曲网络

python - 查看keras嵌入层的输出

python - 如何在 Hy 中构建 Python 模块?

python - 'ascii' 编解码器无法解码位置 319 : ordinal not in range(128)? 中的字节 0xef

python - 用于设置 corelimit 的 Python 的 C 等价物