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

python scott 207℃ 0评论

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

1
2
3
4
5
6
7
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.
    >"
">"
1
2
3
4
5
6
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)()
1
2
3
4
5
6
7
8
9
10
11
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)
1
2
3
4
5
conn = sqlite3.connect('ipaddress.sqlite3.db')
c = conn.cursor()
c.execute('select * from ipdata')
writer = UnicodeWriter(open("export_data.csv>", "wb>"))
writer.writerows(c)

原文:http://blogread.cn/it/article/4884?f=hot1

转载请注明:osetc.com » 使用python将Sqlite中的数据直接输出为CVS

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址