如何在不知道行号的情况下将文件读取为以给定单词开头的字符串? [英] How can I read a file to a string starting at a given word without knowing the line number?

查看:61
本文介绍了如何在不知道行号的情况下将文件读取为以给定单词开头的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在日志文件中有测试结果,其格式如下:

I have test results in a log file that are formatted like:

无用信息

无用信息

=====================

======================

有用的信息

有用的信息

=====================

======================

测试成功

每个部分中的行数可以变化,因此我想检查双等号'=='的首次出现,并将该行读取到文件末尾成为一个字符串.目前,我正在使用以下代码将整个文件读入字符串.

The number of lines in each section can vary, so I want to check for the first appearance of the double equal character '==' and read that line until the end of the file into a string. Currently I'm using the following code to read the whole file into the string.

with open ("Report.txt", "r") as myfile:
    data = myfile.read()

感谢您的帮助!

推荐答案

useful = []
with open ("Report.txt", "r") as myfile:
    for line in myfile:
        if "===" in line:
            break
    for line in myfile:
        useful.append(line)
a_string = "".join(useful)

但是我更喜欢将其隐藏在生成器中,像这样:

I would however prefer to hide it away in a generator, like this:

def report_iterator():
    with open ("Report.txt", "r") as myfile:
        for line in myfile:
            if "===" in line:
                break
        for line in myfile:
            yield line

for line in report_iterator():
    # do stuff with line

所有过滤和分类都是在生成器函数中完成的,您可以将过滤输入"的逻辑与使用输入的逻辑"分开.

All the filtering and nitpicking is done in the generator function, and you can separate the logic of "filtering input" from the logic of "working with the input".

这篇关于如何在不知道行号的情况下将文件读取为以给定单词开头的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆