使用python将json文件导入mongoDB

2024-06-01 14:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试导入时遇到此错误:

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数据

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


Tags: inimportclientjsonfordb错误page
1条回答
网友
1楼 · 发布于 2024-06-01 14:21:16

1.将json文件放在项目存储库中,然后使用它进行读取

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

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

相关问题 更多 >