我对Python相对来说比较陌生,对MongoDB也是一个新手,因此我只关心获取文本文件并转换它们。我目前正在尝试使用JSON中的一堆.txt文件将它们移动到MongoDB中。因此,我的方法是打开目录中的每个文件,读取每行,将其从JSON转换为字典,然后将该行作为JSON作为字典进行重写。然后它将以一种格式发送到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()但它不是写作。
哪个......作为一个经验法则,如果你没有得到你想要的效果,那么你在某个地方犯了一个错误。
有没有人有什么建议?