Python實現將SQLite中的數據直接輸出為CVS的方法示例
本文實例講述了Python實現將SQLite中的數據直接輸出為CVS的方法。分享給大家供大家參考,具體如下:
對于SQLite來說,目前查看還是比較麻煩,所以就像把SQLite中的數據直接轉成Excel中能查看的數據,這樣也好在Excel中做進一步分數據處理或分析,如前面文章中介紹的《使用Python程序抓取新浪在國內的所有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)
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
- Python實現將sqlite數據庫導出轉成Excel(xls)表的方法
- Python解析excel文件存入sqlite數據庫的方法
- Python操作sqlite3快速、安全插入數據(防注入)的實例
- Python標準庫之sqlite3使用實例
- python操作數據庫之sqlite3打開數據庫、刪除、修改示例
- 在Python中使用SQLite的簡單教程
- python實現在sqlite動態(tài)創(chuàng)建表的方法
- Python Sqlite3以字典形式返回查詢結果的實現方法
- python操作sqlite的CRUD實例分析
- 詳解Python 數據庫 (sqlite3)應用
- Python實現excel轉sqlite的方法
相關文章
基于Python創(chuàng)建語音識別控制系統(tǒng)
這篇文章主要介紹了通過Python實現創(chuàng)建語音識別控制系統(tǒng),能利用語音識別識別說出來的文字,根據文字的內容來控制圖形移動,感興趣的同學可以關注一下2021-12-12

