sanvi4 sanvi4 - 12 days ago 5
Python Question

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

Answer

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