本文實例講述了Python實現將SQLite中的數據直接輸出為CVS的方法。分享給大家供大家參考,具體如下:
對于SQLite來說,目前查看還是比較麻煩,所以就像把SQLite中的數據直接轉成Excel中能查看的數據,這樣也好在Excel中做進一步分數據處理或分析,如前面文章中介紹的《使用Python程序抓取新浪在國內的所有IP》。從網上找到了一個將SQLite轉成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)更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選