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