在 Python 中,将文件拆分为多行,然后仅打印以

In Python, split a file into lines, and then print only ones starting with

所以,我有一个文件,例如,'test.txt'。我只想检查并打印以 'result':

开头的行

test.txt 看起来像这样:

this is a test file
used to test a python script
result 1
dummy text goes here
result is nice
blah blah blah
the end

然后,我想要的是像这样的仅打印输出:

result 1
result is nice

我在尝试解决这个问题时遇到了困难,因为显然我不能使用 startswith() 函数,因为当我拆分文件时它变成了一个列表,这是我上次尝试的代码:

with open('test.txt', 'r') as text:
     lines=text.readlines()
     for x in lines:
          if lines[x].startswith('result'):
               print(lines[x])

这让我收到错误消息:

Traceback (most recent call last):   
File "test.py", line 10, in <module>
if lines[x].startswith('result'):
TypeError: list indices must be integers or slices, not str

我可以做什么呢?提前致谢。

在您创建的循环中,所有行都已分配给行列表,并且您在循环中将它们依次分配给变量 x。这就是为什么在循环内访问它时可以直接使用 x 访问它的原因。

with open('test.txt', 'r') as text:
    lines = text.readlines()
    for x in lines:
        if x.startswith('result'):
            print(x)

我会这样重写你的循环:

with open('test.txt', 'r') as f_in:
     for line in f_in:
          if line.startswith('result'):
               print(line.rstrip())

或者,如果您想保留所有有问题的行,您可以编写一个过滤器:

with open('test.txt') as f_in:
    those_lines=[line.rstrip() for line in f_in if line.startswith('result')]
    # all the lines in question...

或者您可以修改第一个循环以保留有问题的行:

those_lines=[]
with open('test.txt', 'r') as f_in:
     for line in f_in:
          if line.startswith('result'):
               those_lines.append(line.rstrip())

那么如果你想打印它们:

print('\n'.join(those_lines))

代码:

lines=text.readlines()

将整个文件读入列表。这不是必需的,因为您只打印单行和测试单行。在这种情况下,逐行遍历文件更为惯用Python。

您可以直接在循环中使用线条。您不需要在这里使用 readlines()。请发现下面的代码可能会有所帮助。

    with open("text.txt", "r") as f:
        for line in f:
            if line.startswith("result"):
                print(line)