Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading