Python MongoDB read/write CSV file

Source: Internet
Author: User
Tags mongoclient readfile

#-*-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]

In the Tvsplst collection of #读取CVS文件并插入到mongoDB数据库
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 on line:
if it = = ' Plstid ':
Listkey.append (' _id ')
Else
Listkey.append (IT)
else:
j = 0
For it on 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 read/write CSV file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.