Parsing text event file in Python
Question: I have a large text file with Event data that I am trying to parse to a csv.
The structure looks like this:

START  
USER: a  
TIME: 1000  
CLICKS: 1  
COMMAND A: 2  
COMMAND B: 1  
END  
START  
USER: b  
TIME: 00  
CLICKS: 1  
COMMAND A: 2  
COMMAND B: 1  
COMMAND C: 1  
END  

The events are separated using the START and END tags and I am trying to parse
it to create a csv file that has each event as a row, and the other attributes
as columns, so in the example above, the columns would be USER, TIME, CLICKS,
COMMAND A, COMMAND B, COMMAND C and the values for each would be the value
after the :

I know that this code will read an individual event:

    
    
    with open('sampleIVTtxt.txt', 'r') as input_data:
    for line in input_data:
        if line.strip() == 'START REPORT':
    break
    for line in input_data:  
        if line.strip() == 'END':
    

Where I am stuck is how to parse the lines within the event block and store
them as columns and values in a csv. I'm thinking for each line within the
event block I need to parse out the column name using regex and then store
those names in an array and use writerow(namesarray) to create the columns.
But I'm not sure how to loop through the whole txt file and store subsequent
event values in those columns.

I am new to python, so any help would be appreciated.


Answer: Something like:

    
    
    import csv
    
    with open('sampleIVTtxt.csv', 'w') as csvfile:
        fieldnames = ['USER', 'TIME','CLICKS','COMMAND_A','COMMAND_B','COMMAND_C']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
    
    with open('sampleIVTtxt.txt', 'r') as input_data:
    for line in input_data:
        thisLine=line.strip()
        if thisLine == 'START':
           myDict={}
        elif "USER" in thisLine:
           myDict['USER'] = thisLine[6:]
         ....and so on....
        elif thisLine == 'END':
          writer.writerow(myDict)
    

