sanvi4
sanvi4

Reputation: 19

How to read a file line by line and get a some string in each line in python

I am trying to read a text file and print a string present in the file

Text file(Test.txt):

Start_set
START: XYZ
PASS: True
PASS: True
PASS: True
END: XYZ
START: PQR
PASS: True
PASS :True
END: PQR
START: ABC
PASS: True
PASS :True
END: ABC
End_set

Following is the python code:

file = open('Test.txt','r')
text = file.read()
output = text.split('START:')[1].split("\n")[0]
print out

Output:

XYZ

But i want to read each line of the file and print the values "XYZ,PQR,ABC" as output . My code prints only "XYZ".I tried with while loop but did not get expected output.

Thanks in Advance

Upvotes: 0

Views: 118

Answers (1)

Sanket Sudake
Sanket Sudake

Reputation: 771

You need lookout all occurrences of START:

Solution:

with open('Test.txt', 'r') as fp:
    for line in fp:
        if line.startswith('START:'):
           print(line.strip().split('START:')[1])

Output:

 XYZ
 PQR
 ABC

Upvotes: 6

Related Questions