本文實(shí)例講述了Python實(shí)現(xiàn)將SQLite中的數(shù)據(jù)直接輸出為CVS的方法。分享給大家供大家參考,具體如下:
對(duì)于SQLite來說,目前查看還是比較麻煩,所以就像把SQLite中的數(shù)據(jù)直接轉(zhuǎn)成Excel中能查看的數(shù)據(jù),這樣也好在Excel中做進(jìn)一步分?jǐn)?shù)據(jù)處理或分析,如前面文章中介紹的《使用Python程序抓取新浪在國(guó)內(nèi)的所有IP》。從網(wǎng)上找到了一個(gè)將SQLite轉(zhuǎn)成CVS的方法,貼在這里,供需要的朋友使用:
import sqlite3import csv, codecs, cStringIOclass 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)
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選