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

yipeiwu_com5年前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中的__future__模块

Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动。有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了。 从Python 2....

python 常见字符串与函数的用法详解

strip去除空格 s = ' abcd efg ' print(s.strip()) #去除所有空格 print(s.lstrip()) #去除左边空格 print(s.rs...

11个Python Pandas小技巧让你的工作更高效(附代码实例)

本文为你介绍Pandas隐藏的炫酷小技巧,我相信这些会对你有所帮助。 或许本文中的某些命令你早已知晓,只是没意识到它还有这种打开方式。 Pandas是一个在Python中广泛应用的数据...

终端命令查看TensorFlow版本号及路径的方法

终端命令查看TensorFlow版本号及路径的方法

如图,简单易懂,先激活tensorflow,然后进入python,输入python语句执行查询: 需要注意的是一定要在激活tensorflow环境后再输入python命令,否则会识别不...

python读取目录下所有的jpg文件,并显示第一张图片的示例

如下所示: # -*- coding: UTF-8 -*- import numpy as np import os from scipy.misc import imread, i...