在文本文件中,计算从字符串“foo”到第一个空行的行数。如果未找到“foo”则引发异常

问题描述 投票:0回答:1

背景:我想从文本文件中读取一些数据到

polars
数据框中。数据从包含字符串
foo
的行开始,并在之后的第一个空行处停止。示例文件
test.txt
:

stuff to skip
more stuff to skip


skip me too

foo bar foobar
1   2   A
4   5   B
7   8   C


other stuff
stuff

pl.read_csv
有参数
skip_rows
n_rows
。因此,如果我可以找到
foo
的行号以及之后第一个空行的行号,我应该能够将数据读入
polars
数据帧。我怎样才能做到这一点?我能找到
skip_rows
:

from pathlib import Path

file_path = Path('test.txt')

with open(file_path, 'r') as file:
    skip_rows = 0
    n_rows = 0
    for line_number, line in enumerate(file, 1):
        if 'foo' in line:
            skip_rows = line_number - 1

但是我怎样才能在不再次扫描文件的情况下找到

n_rows
呢?此外,解决方案必须处理没有包含
foo
的行的情况,例如

stuff to skip
more stuff to skip


skip me too

1   2   A
4   5   B
7   8   C


other stuff
stuff

在这种情况下,我想返回一个值来指示未找到

foo
,或者引发异常,以便调用者知道出了问题(也许是
ValueError
异常?)。

python file-io python-polars text-parsing
1个回答
0
投票

你可以尝试:

start, end = None, None
with open("your_file.txt", "r") as f_in:
    for line_no, line in enumerate(map(str.strip, f_in)):
        if line.startswith("foo"):
            start = line_no
        elif start is not None and line == "":
            end = line_no
            break
    else:
        print("foo not found!")

if start is not None:
    print(f"{start=} {end=}")

打印(包含您问题中的第一个输入):

start=6 end=10
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.