0
我是python和mongodb的初學者。我從多個CSV文件數據推送到的MongoDB數據庫所在的新數據應該替換mongodb.I現有的數據認爲這將是有幫助的,而看節目, 我的代碼:'Keyerror'在更新mongodb時
from pymongo import MongoClient
import csv
path = 'C://test//xxx.csv'
csvfile = open(path, "r")
reader = csv.DictReader(csvfile)
mongo_client=MongoClient()
db=mongo_client.production
header= ["Instrument Name", "Date", "High", "Low", "Open", "Close", "Prev Close", "Volume"]
for each in reader:
row={}
k={}
for field in header:
if field=="Instrument Name":
row[field]=each[field]
k[field]=row[field]
print k[field]
elif field=="Date":
row[field]=datetime.datetime.strptime(each[field], "%Y-%m-%d %H:%M:%S")
else:
row[field]=float(each[field])
#row[field]=each[field]
print row
db.test.find_and_modify(query={'Instrument Name':k[field]},sort=1,update={row})
csvfile.close()
輸出:
BANKNIFTY15MARFUT
{'Volume': 200.0, 'Prev Close': 18919.8, 'Instrument Name': 'BANKNIFTY15MARFUT', 'High': 19350.2, 'Low': 19350.2, 'Date': datetime.datetime(2015, 1, 13, 9, 15), 'Close': 19350.2, 'Open': 19350.2}
KeyError Traceback (most recent call last)
<ipython-input-1-0f0bc16df1c5> in <module>()
263 print row
264 #row[field]=each[field]
--> 265 db.test.find_and_modify(query={"Instrument Name":k[field]},sort=1,update={row})
266 csvfile.close()
267
KeyError: 'Volume'
即使「卷」出現在我的CSV它拋出KeyError異常的Volume.Assist我解決這個問題