使用Python读取mongoDB写入csv文件

方法一: 使用pandas 写入csv文件

import pandas as pd
#任意的多组列表
a = ["a", "b", "c"]
b = ["d", "e", "f"]
#字典中的key值即为csv中列名
dataframe = pd.DataFrame({'one_name': a, 'two_name': b})
#将DataFrame存储为csv,index表示是否显示行名,default=True
dataframe.to_csv("test.csv", index=False, sep=',')

方法二:使用csv库一行一行的写入csv文件

import csv
with open("test.csv","w", 'utf-8') as csvfile: 
    writer = csv.writer(csvfile)

    #先写入columns_name
    writer.writerow(["index","a_name","b_name"])
    #写入多行用writerows 每一个列表为一行
    writer.writerows([[0,1,3],[1,2,3],[2,3,4]])

示例:使用pymongo读取mongo数据库内容并写入csv文件

import codecs
import csv
import pymongo
# 链接mongo数据库
mongo_client = pymongo.MongoClient('127.0.0.1', 27017)
db = mongo_client.ceis_nlp
my_collection = db.twitter_tweet
#查询库中数据
cursor = my_collection.find()
#打开csv文件
with codecs.open('data.csv', 'w', 'utf-8') as csvfile:
    writer = csv.writer(csvfile)
    # 先写入columns_name
    writer.writerow(["name", "content", "topic", "at"])
    #写入多行用writerows
    for data in cursor:
        writer.writerows([[data["name"], data["content"], data["topic"], data["at"]]])

你可能感兴趣的:(python学习笔记,csv,python,pandas,mongo)