首页 > 解决方案 > 使用python将json文件导入mongoDB

问题描述

尝试导入时出现此错误:

Traceback (most recent call last):
  File "C:\PythonSC\module21.py", line 8, in <module>
    page = open('c:\restaurants\restaurants.json','r')
OSError: [Errno 22] Invalid argument: 'c:\restaurants\restaurants.json'

这是我尝试导入的源代码:

import json
import pymongo
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.restaurants
collection = db.restaurantsCollection
page = open('c:\restaurants\restaurants.json','r')
dataset = json.loads(page.read())

for item in dataset:
    collection.insert(item)

for item in collection.find():
    print(item)

这是来自https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json的示例 json 数据

我仍然不明白为什么会出现这个错误,我希望有人能帮帮我。非常感谢。

标签: pythonmongodb

解决方案


1.将您的json文件放在您的项目存储库中,然后将其用于阅读。

f= open("[file_name]","r+")

2.其他方式(第二种方法)是使用os模块获取文件的位置并将其用作 path=os.getcwd()+[append your file name] open(path,'r+');


推荐阅读