使用python将Sqlite中的数据直接输出为CVS

标点符 2012-01-29 20:25:53 累计浏览 3,728 次

    对于SQLite来说,目前查看还是比较麻烦,所以就像把SQLite中的数据直接转成Excel中能查看的数据,这样也好在Excel中做进一步分数据处理或分析,如上篇文章中介绍的IP抓取的IP数据。从网上找到了一个将SQLite转成CVS的方法,贴在博客里,供需要的朋友使用:

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(\'ipaddress.sqlite3.db\')
c = conn.cursor()
c.execute(\'select * from ipdata\')
writer = UnicodeWriter(open("export_data.csv", "wb"))
writer.writerows(c)

同分类推荐文章

  1. 国产数据库迁移:真正花时间的从来不是搬数据 (2026-11-14 04:10:02)
  2. 由于con$.con#值达到极限,触发数据库增加约束报ORA-600 12807错误 (2026-11-14 03:40:02)
  3. MongoDB 离线提取工具—mongoext (2026-11-13 18:10:02)

查看更多 数据库 文章 →

建议继续学习

  1. 用Hyer来进行网站的抓取 (累计阅读 158,837)
  2. 配置Nginx+uwsgi更方便地部署python应用 (累计阅读 109,258)
  3. 程序员技术练级攻略 (累计阅读 36,063)
  4. python实现自动登录discuz论坛 (累计阅读 33,281)
  5. python编程细节──遍历dict的两种方法比较 (累计阅读 21,009)
  6. 每个程序员都应该学习使用Python或Ruby (累计阅读 18,311)
  7. Chrome和goagent的配置方法,你懂的 (累计阅读 17,493)
  8. 30分钟3300%性能提升――python+memcached网页优化小记 (累计阅读 14,113)
  9. 使用python爬虫抓站的一些技巧总结:进阶篇 (累计阅读 13,777)
  10. 我的PHP,Python和Ruby之路 (累计阅读 13,720)