Skip to content

Instantly share code, notes, and snippets.

@icedraco
Created November 27, 2014 12:04
Show Gist options
  • Save icedraco/78d9879f2171ecebcbfb to your computer and use it in GitHub Desktop.
Save icedraco/78d9879f2171ecebcbfb to your computer and use it in GitHub Desktop.
SQLite3 to Tab-Delimiter Text file converter
#!/usr/bin/python
# .-=[ sql3-to-tab ]=======================================================-. #
# | SQLite3 to Tab-Delimited TXT Converter by IceDragon of QuickFox.org | #
# |-------------------------------------------------------------------------| #
# | This script converts an SQLite3 database to a tab-delimited text file. | #
# | Particularly useful to export data from a database into applications | #
# | that allow it. | #
# |-------------------------------------------------------------------------| #
# | NOTE: This script does not yet support \n characters in entries! | #
# '-=============================================================[ 1.0.0 ]=-' #
###--# Imports #--###
import sqlite3
from sys import argv
__author__ = "Kyle Storm <icedragon@quickfox.org>"
###--# Entrypoint #--###
def main( argv ):
# Handling command-line parameters.
if len(argv) < 3:
print "Syntax: %s <db_file> <table> [out_file]" % argv[0]
raise SystemExit(0)
cmd, db_file, table = argv[:3]
if len(argv) > 3:
out_file = argv[3]
else:
out_file = db_file.rsplit('.',1)[0] + '.txt'
# Getting data from the database.
data = sqlite3.connect( db_file ).execute("SELECT * FROM %s" % table).fetchall()
# Opening output file.
fd = open( out_file, 'w' )
counter = 0
for entry in data:
# Ensuring the entry list is all strings. join() would fail otherwise.
entry_list = []
for element in entry:
entry_list += [ str(element) ]
fd.write( "\t".join( entry_list ) + "\n" )
counter += 1
fd.close()
print "%d entries exported to %s" % (counter,out_file)
raise SystemExit(0)
###--# Initialization #--###
if __name__ == "__main__":
main( argv )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment