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