如何使用python将文本文件导入SQLite3表

时间:2018-08-11 19:02:58

标签: python sqlite

我目前有一个电影的txt文件,其中包含movieID,电影名称和流派。 示例:

1,Toy Story (1995),Animation|Children's|Comedy
2,Jumanji (1995),Adventure|Children's|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama
5,Father of the Bride Part II (1995),Comedy

我正在尝试将此文件导入到使用Python创建的SQLite3表中:

import sqlite3

conn = sqlite3.connect('CSC 452 Final.db')
c=conn.cursor()

删除表格

c.execute('''DROP TABLE IF EXISTS temp_movie''')
print("Table temp_movie dropped.")

创建电影表

c.execute('''CREATE TABLE temp_movie (
    MovieID          NUMERIC (5),
    movie_title_year VARCHAR2 (255),
    movie_categories VARCHAR2 (255),
    CONSTRAINT movies_movieID_PK PRIMARY KEY (
        MovieID
    ))''')
print("Table temp_movie successfully created.")
conn.commit()

将分隔符为','的文本文件导入该数据库的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以读取txt文件并在,上拆分:

file_data = [i.strip('\n').split(',') for i in open('filename.txt')]
new_data = [[int(a), *b] for a, *b in file_data] #convert string id to integer
conn = sqlite3.connect('CSC 452 Final.db')
c = conn.cursor()
c.executemany('INSERT INTO temp_movie VALUES (?, ?, ?)', new_data)

答案 1 :(得分:1)

我本可以使用python csv模块来做到这一点:

with open(<txt file>,'rb') as f: 
    dic_reader = csv.DictReader(f)
    value_list = [(each_row['MovieID'], each_row['movie_title_year'], each_row['movie_title_year']) for each_row in dic_reader]

c.executemany("INSERT INTO t (MovieID, movie_title_year, movie_title_year) VALUES (?, ?);", value_list)
conn.commit()
conn.close()