qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          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()

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

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

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 青铜峡市| 伊金霍洛旗| 诸城市| 灯塔市| 从化市| 阜阳市| 花莲市| 尤溪县| 安化县| 五原县| 中牟县| 宁明县| 西充县| 棋牌| 安吉县| 永城市| 湘阴县| 澄城县| 佳木斯市| 奉化市| 扎赉特旗| 磐石市| 富宁县| 马尔康县| 清镇市| 安徽省| 大连市| 深水埗区| 长葛市| 临夏市| 凤冈县| 山阴县| 思南县| 河东区| 义乌市| 渝中区| 武川县| 广丰县| 镇平县| 汝州市| 京山县|