我是比較新的Python和非常新的MongoDB(正因爲如此,我只能用走的是文本文件,並將其轉換有關)。我目前正在嘗試使用JSON中的一堆.txt文件將它們移動到MongoDB中。所以,我的做法是在目錄中打開每個文件,讀取每一行,它從JSON轉換爲一個字典,然後過寫行爲 JSON作爲字典。然後,它會在一個格式發送到MongoDB的的Python:轉換JSON到Python字典的整個目錄發送到MongoDB的
(如果有我的道理任何瑕疵,請指出來)
目前,我已經寫了這一點:
"""
Kalil's step by step iteration/write.
JSON dumps takes a python object and serializes it to JSON.
Loads takes a JSON string and turns it into a python dictionary.
So we return json.loads so that we can take that JSON string from the tweet and save it as a dictionary for Pymongo
"""
import os
import json
import pymongo
rootdir='~/Tweets'
def convert(line):
line = file.readline()
d = json.loads(lines)
return d
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file, 'r')
lines = f.readlines()
f.close()
f=open(file, 'w')
for line in lines:
newline = convert(line)
f.write(newline)
f.close()
但它不寫。 其中......作爲一個經驗法則,如果你沒有得到,你想要的效果,你犯了一個錯誤的地方。
有沒有人有任何建議?
我是個白癡。非常感謝。 我不能相信我並沒有意識到,巨大的,張開的邏輯關於Python字典作爲一塊內存錯誤。 – Noc 2012-07-18 17:17:58