我对 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()
但这不是写作。哪个...根据经验,如果您没有得到想要的效果,那么您在某处犯了错误。
有没有人有什么建议?