python - 使用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 数据
我仍然不明白为什么会出现这个错误,我希望有人能帮帮我。非常感谢。
解决方案
1.将您的json文件放在您的项目存储库中,然后将其用于阅读。
f= open("[file_name]","r+")
2.其他方式(第二种方法)是使用os模块获取文件的位置并将其用作
path=os.getcwd()+[append your file name]
open(path,'r+');
推荐阅读
- jenkins - Jenkins 中的 HTML 报告
- heroku - 运行混合发布时,Heroku 审查应用程序上的 Elixir 构建失败并出现 (ArgumentError) 参数错误:erlang.binary_to_atom(nil, :utf8)
- python - 绘制图表但存在范围问题
- android - 为什么我在带有 Kotlin 的 Android Studio 中使用 async{} 后会得到 LiveData 的 null 值?
- html - 在 vb.net 中的 HTML5 类型周如何获取值?
- android - 将 MutableLiveData 传递给其他 ViewModel 是否有效?
- android - Xamarin Forms Icons 出于某种原因转向我认为汉字
- assembly - 在 SysV ABI 中的 edi/esi 中传递参数
- android - audioserver 错误阻止 android ROM 启动
- python - Ansible 基本动态清单