qileilove

          blog已經(jīng)轉(zhuǎn)移至github,大家請?jiān)L問 http://qaseven.github.io/

          python批量導(dǎo)入MongoDB數(shù)據(jù)庫

           由于源文件不是MongoDB支持的JSON和BSON 格式的數(shù)據(jù), 所以只能將源數(shù)據(jù)轉(zhuǎn)變格式后, 用腳本將其導(dǎo)入,所測數(shù)據(jù)為中科院信工所提供的數(shù)據(jù)。(這也是在信工所接觸的第一個(gè)寫程序的活。)源碼如下:
          #!/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()

          posted on 2014-04-03 11:26 順其自然EVO 閱讀(751) 評論(0)  編輯  收藏 所屬分類: 測試學(xué)習(xí)專欄

          <2014年4月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 精河县| 虎林市| 淮安市| 鹤山市| 青海省| 巩留县| 翁源县| 章丘市| 兴宁市| 信宜市| 陆丰市| 萨迦县| 新干县| 贞丰县| 神农架林区| 河南省| 沙坪坝区| 双江| 密山市| 高尔夫| 上饶县| 满洲里市| 邛崃市| 休宁县| 潜山县| 塘沽区| 丰城市| 南开区| 格尔木市| 疏勒县| 班玛县| 灵宝市| 沙田区| 衡阳县| 巴彦淖尔市| 巴彦县| 阿巴嘎旗| 贵港市| 蒙阴县| 甘肃省| 德化县|