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

Time:02-02

So, I have a file, for example, 'test.txt'. I want to check and print only the lines starting with 'result':

test.txt looks like this:

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

Then, what i want is for the print only output like this:

result 1
result is nice

I'm having difficulties trying to figure this one out, because apparently i can't use startswith() function, since when i split the file it becomes a list, here's the code I last tried:

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

And that gets me the error message:

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

What can I do instead? Thanks in advance.

CodePudding user response:

In the loop you created, all the lines are already assigned to the lines list, and you assign them to the variable x sequentially with the loop. That's why you can access it directly using x when accessing it inside the loop.

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

CodePudding user response:

I would rewrite your loop this way:

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

Alternatively, you can write a filter if you want to keep all the lines in question:

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...

Or you can modify the first loop to keep 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())

Then if you want to print them:

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

The code:

lines=text.readlines()

reads the entire file into a list. This is not necessary since you are only printing single lines and testing single lines. It is more idiomatic Python to loop over the file line by line in this case.

CodePudding user response:

You can use lines in a loop directly. You don't need to use readlines() here. Please find the code below can be helpful.

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