[英]How to Parse text file in python based on condition
I have a text file that I want to parse based on the condition that if I find the match phrase in the line then I have to jump to the next line to fetch the value{unfortunately that's how the reports logs are generated}. 我有一个文本文件,要根据以下条件进行分析:如果我在该行中找到匹配短语,则必须跳到下一行以获取值{很遗憾,这就是生成报告日志的方式}。 I have created _dict to check my key and fetch my values in the next line. 我创建了_dict以检查我的密钥并在下一行中获取我的值。
Lines = f1.readlines()
numlines = len(Lines)
f1.close()
f1 = open('Testlog.txt','r')
f2 =open('writetoFile','r+')
f3 =open('Results.txt','w')
new_line="Test Name SubTest passed failed status "
f3.write(new_line)
f3.write("\n")
while i < numlines:
line=f1.readline()
if "Test Name" in line:
f2.write(line)
i=i+1
line =f1.readline()
if "true" in line:
f2.write(line)
line = line.strip('\n ')
#print line
data = re.split(r"\s{2,}",line)
Test_Name=data[4]
SubTest=data[6]
passed=data[7]
failed=data[8]
status=data[9]
result = Test_Name + " " + SubTest + " " + passed + " " + failed + " " + status
print result
f3.write(result)
f3.write("\n")
i=i+1
I was wondering if there better way to do this 我想知道是否有更好的方法可以做到这一点
What is your method for parsing the line? 您解析行的方法是什么? Can you post sample code, that will help. 您可以张贴示例代码吗,这会有所帮助。
To answer your second question, you could make a Dictionary in which each key refers to a List, then you can use a for loop to iterate through each of the values (or whatever you'll need) 要回答第二个问题,您可以制作一个Dictionary,其中每个键都指向一个列表,然后可以使用for循环遍历每个值(或您需要的任何值)
foo = { 1 : ['a','b','c'] }
for value in foo[1]:
print(value)
prints abc 打印abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.