如何打印最后出现的字符串加上下面的N行

2024-10-01 13:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个文件输出解析器,但在如何打印最后一个字符串+下面N行数时遇到了问题。输出文件通常小于2MB,所以我应该不会有任何问题读取文件到内存,但如果有一个更优雅的解决方案,这将是很好的学习

我曾尝试将行保存到列表中,然后打印出最后出现的行,但它会将行拆分为单词,因此列表最终很难处理。我也有程序读取总行数需要提前打印,如果有其他解决方案比我所尝试的

def coord():
    stdOrn = 'Standard orientation'
    coord = {}
    found = False
    with open(name, 'r') as text_file:
        for line in text_file:
            if stdOrn in line:
                found = True
            elif 'Rotational constants (GHZ)' in line:
                found = False
            elif found:
                coord = line

    outFile.write(coord)

Tags: 文件内存字符串textinfalse解析器列表
1条回答
网友
1楼 · 发布于 2024-10-01 13:26:59

您可以将其作为字符串加载,使用.rfind()获取最后一次出现的索引,然后从最后一个索引执行字符串切片

stdOrn = 'Standard orientation'
found = False
with open(name, 'r') as text_file:
    file_contents = text_file.read()
    last_appearance = file_contents.rfind(std0rn)
    following_n_lines = file_contents[last_appearance:]

相关问题 更多 >