android将sqlite数据表导出到csv格式文件,是否可以将表sqlite3表导出到csv或类似文件?...

我使用了the docs中稍加修改的示例类将这个非常基本的脚本组合在一起;它只需将整个表导出到CSV文件:import sqlite3

import csv, codecs, cStringIO

class UnicodeWriter:

"""

A CSV writer which will write rows to CSV file "f",

which is encoded in the given encoding.

"""

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):

# Redirect output to a queue

self.queue = cStringIO.StringIO()

self.writer = csv.writer(self.queue, dialect=dialect, **kwds)

self.stream = f

self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):

self.writer.writerow([unicode(s).encode("utf-8") for s in row])

# Fetch UTF-8 output from the queue ...

data = self.queue.getvalue()

data = data.decode("utf-8")

# ... and reencode it into the target encoding

data = self.encoder.encode(data)

# write to the target stream

self.stream.write(data)

# empty queue

self.queue.truncate(0)

def writerows(self, rows):

for row in rows:

self.writerow(row)

conn = sqlite3.connect('yourdb.sqlite')

c = conn.cursor()

c.execute('select * from yourtable')

writer = UnicodeWriter(open("export.csv", "wb"))

writer.writerows(c)

希望这有帮助!

编辑:如果希望CSV中有标题,快速的方法是在从数据库中写入数据之前手动添加另一行,例如:# Select whichever rows you want in whatever order you like

c.execute('select id, forename, surname, email from contacts')

writer = UnicodeWriter(open("export.csv", "wb"))

# Make sure the list of column headers you pass in are in the same order as your SELECT

writer.writerow(["ID", "Forename", "Surname", "Email"])

writer.writerows(c)

编辑2:若要输出管道分隔列,请注册自定义CSV方言并将其传递到编写器,如下所示:csv.register_dialect('pipeseparated', delimiter = '|')

writer = UnicodeWriter(open("export.csv", "wb"), dialect='pipeseparated')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值