Python implements a method example that outputs data directly from SQLite to CVS

  • 2020-06-12 09:51:04
  • OfStack

This article illustrates an Python implementation that outputs data directly from SQLite to CVS. To share for your reference, specific as follows:

For SQLite, it is still troublesome to check at present, so it is just like transferring the data in SQLite directly to the data that can be viewed in Excel, so as to make further processing or analysis of the score data in Excel, such as "Using Python program to grab all IP of Sina in China" introduced in the previous article. I found a way to convert SQLite to CVS from the Internet and posted it here for the friends who need it:


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)

More about Python related content interested readers to view this site project: "common database operations Python skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: