我使用文档中经过稍微修改的示例类将这个非常基本的脚本组合在一起;它只是将整个表导出到CSV文件:
import sqlite3import csv, precs, cStringIOclass UnipreWriter: """ A CSV writer which will write rows to CSV file "f", which is enpred 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.enprer = precs.getincrementalenprer(encoding)() def writerow(self, row): self.writer.writerow([unipre(s).enpre("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.depre("utf-8") # ... and reenpre it into the target encoding data = self.enprer.enpre(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 = UnipreWriter(open("export.csv", "wb"))writer.writerows(c)希望这可以帮助!
编辑: 如果要在CSV中设置标题,快速的方法是在从数据库写入数据之前手动添加另一行,例如:
# Select whichever rows you want in whatever order you likec.execute('select id, forename, surname, email from contacts')writer = UnipreWriter(open("export.csv", "wb"))# Make sure the list of column headers you pass in are in the same order as your SELECTwriter.writerow(["ID", "Forename", "Surname", "Email"])writer.writerows(c)编辑2: 要输出用管道分隔的列,请注册一个自定义CSV方言并将其传递到writer,如下所示:
csv.register_dialect('pipeseparated', delimiter = '|')writer = UnipreWriter(open("export.csv", "wb"), dialect='pipeseparated')这是可以与自定义方言一起使用的各种格式设置参数的列表。



