This script is meant to parse and sort a list from a csv file and save to a newly created csv file, including headers.
I triyng to include the write function to save the output of this parser to a new csv file with the following. This code create a csv but record the headers only and in one column.
Here's the input:
Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,Params,
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{},
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{},
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : Home},
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : Home},
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : QuickAndEasy},
Here's the output I'd like to get saved to csv:
Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,TabName,RecipeID,Type,SearchWord,IsFromLabel,
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,,
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,,
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,,
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,,
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,QuickAndEasy,,,,,
The code:
import csv
def printfields(keys, linesets):
output_line = ""
for key in keys:
if key in linesets:
output_line += linesets[key] + ","
else:
output_line += ","
print output_line
def csvwriter(reader, path):
"""
write reader to a csv file path
"""
with open(path, "w") as csv_file:
writer = csv.writer(csv_file, delimiter=",")
for line1 in line:
if line1 in path:
writer.writerow(line1)
if __name__ == "__main__":
fields = [
"UserID", "tabName", "RecipeID", "type", "searchWord", "isFromLabel", "targetUID"
]
mappedLines = {}
with open('test.csv', 'r') as f:
reader = csv.DictReader(f)
for line in reader:
fieldPairs = [
p for p in
line['Params'].strip().strip('}').strip('{').strip().split(';')
if p
]
lineDict = {
pair.split()[0].strip(): pair.split(':')[1].strip()
for pair in fieldPairs
}
mappedLines[reader.line_num] = lineDict
path = "output.csv"
csvwriter(reader, path)
for key in sorted(mappedLines.keys()):
linesets = mappedLines[key]
printfields(fields, linesets)
defstmt you need to add indent. docs.python.org/2/tutorial/controlflow.html#defining-functions"wd"isn't a valid string foropen, indentation is still wrong afterif line1 in pathand missing:).