[Python] How do I make one python dictionary to csv with headers?

Discussão em 'Python' iniciado por Stack, Abril 4, 2025.

  1. Stack

    Stack Membro Participativo

    I've been sitting for some time with a task to import serverlogs from a .txt file, write it out to a python dictionary and write it further out to a csv file to make it readable in a database. When I open it in fx. excel, I want it to be listed with headers.

    EDIT: I need this to be generic in the way that I can load a log file of any length and still get everything. Edit done.

    I'm stuck at the part of writing the dictionary down to the csv file. My following script looks like the following, and the seperated, out commented files are tries i've used to make it write it out.

    lineArray = []
    timeArray = []
    typeArray = []
    whoArray = []
    idArray = []
    msgArray = []

    infile = open('C:\SomeArea\data.txt', 'r')
    dictionary = {'time','type','who','id','msg'}
    for line in infile:
    timeInString = line[:24]
    timeInStringStripped = timeInString.strip()
    timeArray.append(timeInStringStripped)
    allTimes = ', '.join(timeArray)

    #The last 4 fields was removed here to take less space

    infile.close()
    dictionary = {'time': allTimes, 'type': allTypes, 'who': allWhos, 'id': allIds, 'msg': allMsgs}


    Half attempts to write it to the csv

    #<><><><><><><><><><><><><><><><><><><><><><><>#
    #str = 'lement1, lement2'
    #arr = ['lement1, lement2']

    #import csv
    #f = open('sometest2.csv', 'wb')
    #wtr = csv.DictWriter(f, dictionary.viewkeys())
    #for element in dictionary.viewitems():
    # print element
    # for e in element:
    # print e
    #wtr.writerow(0)
    #f.close()
    #wtr.writerows(allTimes)
    #wtr.writerows(allTypes)
    #wtr.writerows(allWhos)
    #wtr.writerows(allIds)
    #wtr.writerows(allMsgs)
    #print dictionary

    #<><><><><><><><><><><><><><><><><><><><><><><>#

    import csv
    f = open('sometest2.csv', 'wb')
    wtr = csv.DictWriter(f, dictionary.viewkeys())
    for row in dictionary: f.write("%s%s" %(delimiter.join([row[name] for name in fieldnames]),lineterminator))

    Continue reading...

Compartilhe esta Página