python mongodb 讀寫CSV檔案

來源:互聯網
上載者:User

標籤:

# -*- coding: utf-8 -*-
import os
import csv
import pymongo
from pymongo import MongoClient

#建立串連
client = MongoClient(‘10.20.4.79‘, 27017)
#client = MongoClient(‘10.20.66.106‘, 27017)
db_name = ‘ta‘ #資料庫名
db = client[db_name]

 

#讀取CVS檔案並插入到mongoDB資料庫 的tvsplst集合中
def InsertDataFromCVS(csvFile):
  strFile = unicode(csvFile,‘utf8‘)
  if os.path.isfile(strFile):
    readFile = file(strFile, ‘rb‘)
    reader = csv.reader(readFile)
    i = 0
    listKey =[]
    sqlDict = {}
    for line in reader:
      i = i + 1
      sqlDict.clear()
      if i == 1:
        for it in line:
          if it == ‘PlstID‘:
            listKey.append(‘_id‘)
          else:
            listKey.append(it)
      else :
        j = 0
        for it in line:
          sqlDict[listKey[j]] = it.decode(‘gbk‘)
          j = j + 1

        try:
          db.tvsplst.insert(sqlDict)
        except:
          print i,sqlDict
    readFile.close()


#測試代碼
strcsvFile=‘D:\\TVSPlst.csv‘
InsertDataFromCVS(strcsvFile)

 

#從mongoDB資料庫中讀取tvsplst資料寫到CSV檔案裡面
def WriteTvsPlsttoCsv(csvFile):
  strFile = unicode(csvFile,‘utf8‘)
  headList =[‘PlstID‘, ‘MediaID‘, ‘PlstDate‘, ‘Hard_STime‘]
  writer = csv.writer(file(strFile, ‘wb‘))
  writer.writerow(headList)
  headList[0]=‘_id‘

  for u in db.tvsplst.find():
    vList = []
    for k in headList:
      vList.append(u[k].encode(‘utf8‘))
      writer.writerow(vList)

#測試代碼
csvfile = ‘D:\\test.csv‘
WriteTvsPlsttoCsv(csvfile)

python mongodb 讀寫CSV檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.