如何使用python中打开文件的数据创建表?

时间:2016-12-01 22:27:37

标签: python python-2.7 python-3.x

import sqlite3


def setup_tracks(db, data_file):
    '''(str, file) -> NoneType
    Create and populate the Tracks table with
    the data from the open file data_file.'''
    data_file.readlines()
    # connect to the database
    con = sqlite3.connect(db)
    # create a cursor
    cur = con.cursor()
    # Create the Tracks table
    cur.execute('CREATE TABLE tracks'+'(Title TEXT, id INTEGER, Time INTEGER)')
    for line in data_file:
        data = line.strip().split(',')
        Title = data[0].strip()
        id = int(data[1].strip())
        s = int(data[2].strip().split(':'))
        Time = int(s[0]*60 + int(s[1]))

        cur.execute('INSERT INTO tracks VALUES(?, ?, ?)'+(Title, id, Time))

        cur.close()
        con.commit()
        con.close()

文件名为tracks.csv。共有三列enter link description here标题,ID,时间。如果我运行此功能,我会收到一些错误,说无法定义' db'。我希望任何人都可以帮助我。

谢谢你!

1 个答案:

答案 0 :(得分:0)

以下是我对该计划的编辑以及一些观察结果。

import sqlite3

def setup_tracks(db, data_file):
    lines = data_file.readlines()
    # connect to the database
    con = sqlite3.connect(db)
    # create a cursor
    cur = con.cursor()
    # Create the Tracks table
    sql = '''create table tracks (Title text, id int, Time int)'''
    cur.execute(sql)

    for line in lines[1:]:
        data = line.strip().split(',')
        Title = data[0].strip()
        id = int(data[1].strip())
        s = data[2].strip().split(':')
        Time = int(s[0]) * 60 + int(s[1])
        Title = Title.replace("'", "''")

        #This line is not working right.
        cur.execute('INSERT INTO tracks VALUES(?, ?, ?)'+(Title, id, Time))

    con.commit()
    con.close()

filename = 'tracks.csv'
f = open(filename, 'r')
setup_tracks('data.db', f)