zoukankan      html  css  js  c++  java
  • 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!!

  • 相关阅读:
    每周总结
    4月9日学习日志
    4月8日学习日志
    4月7日学习日志
    4月6日学习日志
    Cypress存取时间为10纳秒的异步SRAM
    超低功耗MCU如何降低功耗
    集成铁电存储器MCU为物联网应用提供出色性能
    读取优先和SRAM-MRAM混合结构
    磁阻式随机存储器MRAM基本原理
  • 原文地址:https://www.cnblogs.com/spaceship9/p/3161161.html
Copyright © 2011-2022 走看看