xls===>csv tables===via python ===> sqlite3.db

I've got some files which can help a little bit to figure out where people are from based on their ID card NO.

 

That file looks like this:

Then I converted it into *.csv format which is basically a text file.

    It's not hard that almost every common document editor has this functionality.

Here is my python codes:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
    To store information into a sqlite database
    Usage: $ python id2sql.py afile.csv idlist.db
    This will invoke afile.csv to create a new database named idlist.db

                                    ----  Alex Liu
    
'''
import sqlite3 as dbapi
import csv
import sys


def createDB(path, destination):
    '''
        use the *.csv path to create a database file
    '''
    csvfilepath = path
    
    con = dbapi.connect(destination)
    con.text_factory = str
    cur = con.cursor()
    cur.execute('CREATE TABLE idtable(code INTEGER, Region TEXT)')
    try:
        with open(csvfilepath,'rb') as idcsv:        # 'rb' coz file csv is an obj
            spamreader = csv.reader( idcsv, delimiter=',', quotechar='|')
            for row in spamreader:
                cur.execute( 'INSERT INTO idtable VALUES (?,?)',( row[1],row[2]) )
            con.commit()    # To update database
        return "database %s updated! :)" % destination
    except:
        return "check the source codes again :("

if __name__=="__main__":
    print createDB(sys.argv[1], sys.argv[2])
        

Run it:

Then, use the sqlite brrowser to check it out:

 

You could see the whole content of it :)

 

Isn't good ??

 

Ha Ha Have fun!!

 

posted @ 2013-06-28 16:40  spaceship9  阅读(607)  评论(0编辑  收藏  举报