dump csv from sqlalchemy [英] dump csv from sqlalchemy

查看:211
本文介绍了dump csv from sqlalchemy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我想以csv文件的形式从数据库(sqlite3)转储表。我使用python脚本与酏剂(基于sqlalchemy)修改数据库。我想知道是否有任何方式转储表我使用到csv。

For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I'm using a python script with elixir (based on sqlalchemy) to modify the database. I was wondering if there is any way to dump the table I use to csv.

我看过sqlalchemy serializer ,但它似乎不是我想要的。我做错了吗?我应该在关闭我的sqlalchemy会话之后调用 sqlite3 python模块,而转为文件吗?

I've seen sqlalchemy serializer but it doesn't seem to be what I want. Am I doing it wrong? Should I call the sqlite3 python module after closing my sqlalchemy session to dump to a file instead? Or should I use something homemade?

推荐答案

有很多方法可以实现这一点,包括一个简单的 os .system()调用 sqlite3 实用程序如果你已经安装,但这里大致是我从Python做的:

There are numerous ways to achieve this, including a simple os.system() call to the sqlite3 utility if you have that installed, but here's roughly what I'd do from Python:

import sqlite3
import csv

con = sqlite3.connect('mydatabase.db')
outfile = open('mydump.csv', 'wb')
outcsv = csv.writer(outfile)

cursor = con.execute('select * from mytable')

# dump column titles (optional)
outcsv.writerow(x[0] for x in cursor.description)
# dump rows
outcsv.writerows(cursor.fetchall())

outfile.close()

这篇关于dump csv from sqlalchemy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆