因此,我正在收集數據並將此數據保存到csv文件中,但出於演示目的,我想根據相關的「訂單」對各個csv文件中的列進行重新排序。Python:對csv文件的列進行重新排序
我用的是這個問題(write CSV columns out in a different order in Python)作爲指導,但我不知道爲什麼我收到錯誤
writeindices = [name2index[name] for name in writenames]
KeyError: % Processor Time
當我運行它。請注意,此錯誤似乎不僅限於字符串% Processor Time'
。
我哪裏錯了?
這裏是我的代碼:
CPU_order=["%"+" Processor Time", "%"+" User Time", "Other"]
Memory_order=["Available Bytes", "Pages/sec", "Pages Output/sec", "Pages Input/sec", "Page Faults/sec"]
def reorder_csv(path,title,input_file):
if title == 'CPU':
order=CPU_order
elif title == 'Memory':
order=Memory_order
output_file=path+'/'+title+'_reorder'+'.csv'
writenames = order
reader = csv.reader(input_file)
writer = csv.writer(open(output_file, 'wb'))
readnames = reader.next()
name2index = dict((name, index) for index, name in enumerate(readnames))
writeindices = [name2index[name] for name in writenames]
reorderfunc = operator.itemgetter(*writeindices)
writer.writerow(writenames)
for row in reader:
writer.writerow(reorderfunc(row))
這裏是輸入CSV文件看起來像一個示例:
,CPU\% User Time,CPU\% Processor Time,CPU\Other
05/23/2016 06:01:51.552,0,0,0
05/23/2016 06:02:01.567,0.038940741537158409,0.62259056657940626,0.077882481554869071
05/23/2016 06:02:11.566,0.03900149141703179,0.77956981074955856,0
05/23/2016 06:02:21.566,0,0,0
05/23/2016 06:02:31.566,0,1.1695867249963632,0
請發佈您的'input_file'的內容! **更新:**特別是標題行。 – schwobaseggl