python 读取 postgreSQL 数据保存CSV文件

本文介绍了一种使用Python的psycopg2模块从PostgreSQL数据库中导出数据到CSV文件的方法,并展示了如何读取这些文件进行数据分析。通过具体代码示例,读者可以了解如何执行SQL查询并将结果保存为CSV格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


self.cursor.copy_expert("COPY (%s) TO STDOUT DELIMITER '`'"%(cmd),open(self.dump_file,"w"))



import psycopg2
import os
import csv
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),"..")
CSV_SEP = '`'

class Test():
def __init__(self):
self.database = 'test'
self.user = '###'
self.host = '###'
self.password = '###'
self.conn = psycopg2.connect("dbname='" + self.database + "' user='" + self.user + "' host='" + self.host + "' password='" + self.password + "'")
self.cursor = self.conn.cursor()
self.dump_file = 'test'

def dump_Test(self):
cmd='select * from public."Table1"'
print cmd
f = "%s_navstrand.csv" % (self.dump_file)
self.cursor.copy_expert("COPY (%s) TO STDOUT DELIMITER '`' CSV " % (cmd), open(f, "w"))

def read_csv2(self):
processcount = 0
f = "%s_navstrand" % (self.dump_file)
with open(f, "r", 1024 * 1024 * 1024) as csv_f:
for line in csv_f:
print line
def read_csv(self):
processcount = 0
f = "%s_navstrand.csv" % (self.dump_file)
with open(f) as csvfile:
lines = csv.reader(csvfile,delimiter='`')
for line in lines:
print line
def get_statistic(self):
self.dump_Test()
self.read_csv()

if __name__ == "__main__":
t = Test()
t.get_statistic()

转载于:https://www.cnblogs.com/dasheng-maritime/p/7153784.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值