Home > Software design >  How to read a .log file in Python
How to read a .log file in Python

Time:04-07

Can you please help me with to code that I can use to read .Log file and then change '-' separated value to different column.

The Content in the file is:

Configured/Initialized - Corrected - 03/13/22 - 07:24:26 - Ack? No - Severity: Low
Battery - Triggered - 03/13/22 - 15:59:48 - Ack? No - Severity: Low
Tension Low- not allowed - Finalized - 03/13/22 - 16:22:25 - Ack? Yes - Severity: Low

CodePudding user response:

just use csv with custom delimiter

import csv
file_object = open("file.log", "w")
reader = csv.reader(file_object, delimiter = "-")
for row in reader:
    print row

CodePudding user response:

Using the CSV reader works but, as @jonrshapre noted in the comments below your post, Tension Low- not allowed will not split things correctly. If the "Tension Low- ..." is correct, then you can use the re module where you split the line at " - ".

import re

with open("file.log", "r") as f:
    data = []
    lines = f.readlines()
    for line in lines:
        # use strip() to remove "\n" from end of line
        data.append(re.split(" - ",line.strip()))

for row in data:
    print (row)

Output:

['Configured/Initialized', 'Corrected', '03/13/22', '07:24:26', 'Ack? No', 'Severity: Low']
['Battery', 'Triggered', '03/13/22', '15:59:48', 'Ack? No', 'Severity: Low']
['Tension Low- not allowed', 'Finalized', '03/13/22', '16:22:25', 'Ack? Yes', 'Severity: Low']
  • Related