栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

可以将表sqlite3表导出到csv或类似吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

可以将表sqlite3表导出到csv或类似吗?

我使用文档中经过稍微修改的示例类将这个非常基本的脚本组合在一起;它只是将整个表导出到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')

这是可以与自定义方言一起使用的各种格式设置参数的列表。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号