如何将一个Python字典导出为带标题的CSV?

0 投票
1 回答
1758 浏览
提问于 2025-04-17 09:12

我最近在处理一个任务,想把服务器日志从一个.txt文件导入,先把它写成一个Python字典,然后再输出到一个csv文件,这样就能在数据库中读取了。当我在比如Excel中打开这个csv文件时,我希望它能有标题行,方便查看。

补充说明:我希望这个过程是通用的,也就是说我可以加载任何长度的日志文件,确保能把所有内容都处理好。补充完毕。

我现在卡在把字典写入csv文件的这一步。我的代码大致如下,下面的分开的、被注释掉的部分是我尝试过的写入方法。

    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}

尝试将数据写入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))

1 个回答

4

问题在于,代码试图写入一个包含列表的字典,而csv.DictWriter其实是需要一个字典的列表。

正确的做法是把每一行数据存储为一个字典。因此,不应该像这样:

dictionary = {'time': allTimes,
              'type': allTypes,
              'who': allWhos,
              'id': allIds,
              'msg': allMsgs}

而应该像这样:

data = [{'time': time_row_1,
         'type': type_row_1,
         'who': who_row_1,
         'id': id_row_1,
         'msg': msg_row_1},

        ...

        {'time': time_row_n,
         'type': type_row_n,
         'who': who_row_n,
         'id': id_row_n,
         'msg': msg_row_n},
       ]

所以,从文件读取的代码应该是:

data = []
for line in infile:
    row = {}
    row['time'] = ...
    row['type'] = ...
    ...
    ...
    data.append(row)

而写入文件的代码应该是:

wtr = csv.DictWriter(open(filename, 'w'), keys)
wtr.writerows(data)

撰写回答