[英]Python dictreader KeyError issue
嘗試從CSV讀取數據時出現鍵錯誤。 以下是寫入csv的代碼,然后是從中讀取的代碼。 Ubuntu上的Python 2.7。 任何幫助表示贊賞!
#setting up the csv
with open(databaseLocal, 'wb') as csvfile:
fieldnames = ['cpu', 'pid', 'memory']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames,
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writeheader()
#Here is one spot where it's written to...
if data[:6] == 'active':
print 'mem info received'
memInfo = data[7:-1]
writer.writerow({'cpu': '_', 'pid': pidValue, 'memory': memInfo})
#and here is where it's read from, there is a KeyError for the line
#where we try to get row['pid]
with open(d, 'rb') as csvfile:
reader = csv.DictReader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
print row['pid']
print row.keys()
當我只打印'row.keys()'時,所有三個鍵都會顯示出來。 不知道為什么我不能訪問'row ['pid']或其他任何內容。
謝謝! 馬特
您正在寫到databaseLocal
,但是試圖從d
讀取。 您確定他們引用的是同一個文件嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.