开发者社区> 问答> 正文

在两个先前已知的字符串之间处理文件的Pythonic方法

我用python处理日志文件。假设我有一个日志文件,其中包含一行START和一行END,如下所示:

START
one line
two line
...
n line
END
我想要的是能够在START和END线之间存储内容以便进一步处理。

我在Python中执行以下操作:

with open (file) as name_of_file:

for line in name_of_file:
    if 'START' in line:  # We found the start_delimiter
        print(line)
        found_start = True
        for line in name_of_file:  # We now read until the end delimiter
            if 'END' in line:  # We exit here as we have the info
                found_end=True
                break
            else:

                if not (line.isspace()): # We do not want to add to the data empty strings, so we ensure the line is not empty
                    data.append(line.replace(',','').strip().split())  # We store information in a list called data we do not want ','' or spaces

if(found_start and found_end):

relevant_data=data

然后我处理relevant_data。

看起来复杂的Python纯度,因此我的问题是:有更多的Pythonic方式吗?

展开
收起
一码平川MACHEL 2019-01-23 15:12:32 1725 0
1 条回答
写回答
取消 提交回答
  • 要执行该操作,您可以使用iter(callable, sentinel)本文中讨论的内容,该内容将在您的案例“结束”(申请后.strip())中读取,直至达到sentinel value。

    with open(filename) as file:

    start_token = next(l for l in file if l.strip()=='START') # Used to read until the start token
    result = [line.replace(',', '').split() for line in iter(lambda x=file: next(x).strip(), 'END') if line]
    2019-07-17 23:26:39
    赞同 展开评论 打赏
问答分类:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载