使用Python在多行文本文件中通过关键字查找行

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

(使用Python 3.12.2) 我有一个名为“text.txt”的多行文件,它有 3 行,如下所示:

第 1 行 --> 你好,世界!

第 2 行 --> MrBeast 很有钱。

第 3 行 --> :3 名平均勇敢玩家

但是我只想打印具有“世界”的行,与其所在的行无关,这意味着我必须首先找到所需的行。我一直在寻找一个可以为我做到这一点的函数,并得出结论,可能没有像

variable.lineindex("desired_string")
这样的东西,并且必须自己编写代码,有什么建议还是我是个白痴?

python python-3.x file-handling file-location
2个回答
1
投票
desired_string = "World"

with open("text.txt", "r") as file:
    for line_number, line in enumerate(file, 1):
        if desired_string in line:
            print(f"Found '{desired_string}' in line {line_number}: {line.strip()}")

如果您只需要第一次出现,您可以中断 if 块。


0
投票

您可以循环遍历每一行并查找包含所需字符串的行,如下所示:

filepath = "C:\\Users\\John Dee\\Desktop\\text.txt"
with open(filepath, 'r') as file_object:
    for line in file_object:
        print(line if 'World' in line else '')

或者如果你想去掉空行,可以使用break语句:

with open(filepath, 'r') as file_object:
    for line in file_object:
        print(line if 'World' in line else '')
        break

注意: 如果使用相对文件路径,则执行

filepath = text.txt
。如果使用绝对文件路径,请注意我使用的文件路径适用于 Windows。

© www.soinside.com 2019 - 2024. All rights reserved.