[英]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): 文字档(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: 以下是python代码:
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 . 但是我想读取文件的每一行并输出值“ XYZ,PQR,ABC”作为输出。 My code prints only "XYZ".I tried with while loop but did not get expected output. 我的代码仅打印“ XYZ”。我尝试了while循环,但未获得预期的输出。
Thanks in Advance 提前致谢
You need lookout all occurrences of START:
您需要查找所有出现的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.