如果在 python 中找到字符串,如何打印文件行

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

我想在 txt 文件中找到给出的字符串时打印行。我有一个这样的 txt 文件。

Supported interface modes:
         * IBSS
         * managed
         * AP
         * AP/VLAN
         * monitor
         * mesh point
         * P2P-client
         * P2P-GO
--
    Supported interface modes:
         * IBSS
         * managed
         * AP
         * AP/VLAN
         * monitor
         * P2P-client
         * P2P-GO
         * P2P-device

要查找的字符串是

AP/VLAN
我编写了这段代码,但问题是代码停在找到的第一个字符串处,我需要打印找到
AP/VLAN
的所有行。

findString = "AP/VLAN"

with open('interfaces.txt') as f:
    lines = f.readlines()
    for line in lines:

        if line.find(findString) != -1:
            print('String Found in Line Number:', lines.index(line) + 1)
            print('Line Content:', line)
python file search
2个回答
0
投票

这是使用

enumerate
而不是
.index()
的更清晰的代码版本,因为您会遇到打印找到的字符串实例的第一个索引而不是循环的当前迭代的错误。还使用
in
运算符代替
.find()
函数。

findString = "AP/VLAN"

with open('eg.txt') as f:
    lines = f.readlines()
    for line_num, line_context in enumerate(lines):
        if findString in line_context:
            print(f'String Found in Line Number: {line_num+1}\nLine Content: {line_context.strip()}')

0
投票

index()
方法将返回给定值的第一个索引。 所以
lines.index(line)
总是返回 5。 在这种情况下,您可以在代码中使用
enumerate()
,如下所示:

findString = "AP/VLAN"

with open('interfaces.txt') as f:
    lines = f.readlines()
    for index, line in enumerate(lines):

        if line.find(findString) != -1:
            print('String Found in Line Number:', lines.index() + 1)
            print('Line Content:', line)
© www.soinside.com 2019 - 2024. All rights reserved.