首先安装pymongo:
1
pip install pymongo
代码实现:用urllib2读取数据,打包成JSON格式插入到mongodb中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from pymongo import MongoClient
try:
from urllib2 importurlopen, Request, HTTPError, URLError
except ImportError:
from urllib.request import urlopen, Request, HTTPError, URLError
result = []
try:
f = urlopen('http://www.dynamsoft.com', timeout=3)
while 1:
tmp = f.read(10240)
if len(tmp) == 0:
break
python 访问 mongodb 需要先安装 pymongo,如下:
pip install pymongotxt 文件格式:
代码如下:
#coding=utf-8from pymongo import MongoClient
conn = MongoClient('127.0.0.1', 27017)
# 连接 test 数据库,没有则自动创建
db = conn.test
# 使用 students 集合,没有则自动创建
students = db.students
# 打开学生信息文件, 并将数据存入到数据库
with open('students.txt', 'r') as f:
for line in f.readlines():
# 分割学生信息
items = line.strip('\r').strip('\n').split(',')
# 添加到数据库
students.insert({ 'stu_id': items[0], 'name': items[1], 'grade': int(items[2]) })
# 数据库查询学生信息并打印出来
for s in students.find():
print(s)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)