python 批量导入MongoDB数据库

由于 源文件 不是 MongoDB 支持的JSON 和 BSON 格式的数据, 所以只能将 源数据 转变格式后, 用脚本 将其导入,所测数据为中科院信工所提供的数据。(这也是在信工所接触的第一个写程序的活。)源码如下:


#!/usr/bin/env python
#encoding:utf-8

###################################

# function: analysis the log in the 'die' to JSON , and 
#output the data to the MongoDB.
# data:  2014/3/31
#History: 1.0 

###################################
import os
import pymongo


def connect_mongodb():
    servers="mongodb://localhost:27017"
    conn = pymongo.Connection(servers)
    print conn.database_names()
    db = conn.my_mongodb            #连接库
    return db

def str_process(string,db):
    d={}
    if string == '\n': 
		return
    string2=str(string)
    print '-----'+string
    string2=string2.split(' ')
    print '---------------'
    print string2
    for i in string2:
        print i
    print '------------'
    string2[3].split('\n')
    d['projectcode']=string2[0]
    d['pagename']=string2[1]
    d['pageview']=string2[2]
    d['bytes']=string2[3][:-1]
    db.user.insert(d)	
    
def file_process(source_file,db):
    string2=''

    f=open(source_file,'r')
    print 'file name :'+source_file

    while True:
	  string2=f.readline()
	  if string2 == '':
	    break
	  string2=str_process(string2,db)
	  print string2

def get_dir_list(dir):  #input the dir ,will output the all filename
    dat0=[]
    for i in os.listdir(dir):
        dat0.append(i)
    return dat0

def all_file_process():
    dir_file_name=''
    dir_list=[]

    dir_file_name=raw_input('please input the dir name:')
    dir_list=get_dir_list(dir_file_name)
    print dir_list
    db=connect_mongodb()
    for i in dir_list:
        if str(i) != 'log_file_process.py':
            file_process(str(i),db)

all_file_process()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值