[Solved] How to parse a file matching all the lines for a string and keep track of count?


  1. Open the file and read all lines
with open("file.txt") as f:  
    lines = f.read().splitlines()
  1. Make a list of lines that contain the word “Error”
data = [ line.lstrip('<').rstrip('>').split('><') for line in lines if 'Error' in line  ]
  1. Get the time and message items from the data list
errors = [ { 'time' : line[0], 'message': line[-1] } for line in data ]  
  1. Sort the errors list by ‘time’ in descending order
errors.sort(key=lambda e : e['time'], reverse=True)  

Note that errors is a list of dictionaries, you can use lists if you like.
If you want to print the results :

print '\n'.join( 'Time {:8} Error {}'.format(e['time'], e['message']) for e in errors )

Output :

Time: 4:02   Error: Error message1
Time: 14:13  Error: Error message2

5

solved How to parse a file matching all the lines for a string and keep track of count?