Python实现将SQLite中的数据直接输出为CVS的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了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字典的概念及常见应用实例详解

Python字典的概念及常见应用实例详解

本文实例讲述了Python字典的概念及常见应用。分享给大家供大家参考,具体如下: 字典的介绍 字典的概念 字典的创建 1. 我们可以通过{}、dict()来创...

python网络编程之TCP通信实例和socketserver框架使用例子

python网络编程之TCP通信实例和socketserver框架使用例子

1.TCP是一种面向连接的可靠地协议,在一方发送数据之前,必须在双方之间建立一个连接,建立的过程需要经过三次握手,通信完成后要拆除连接,需要经过四次握手,这是由TCP的半关闭造成的,一方...

python 画二维、三维点之间的线段实现方法

python 画二维、三维点之间的线段实现方法

如下所示: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt # 打开画图窗口1,在...

介绍Python中的一些高级编程技巧

 正文: 本文展示一些高级的Python设计结构和它们的使用方法。在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求、对数据一致性的要求或是对索引的要求等,...

Python实现正弦信号的时域波形和频谱图示例【基于matplotlib】

Python实现正弦信号的时域波形和频谱图示例【基于matplotlib】

本文实例讲述了Python实现正弦信号的时域波形和频谱图。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- # 正弦信号的时域波形与频谱图 impor...