简体   繁体   English

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

[英]How do I import a text file into a SQLite3 table using python

I currently have a txt file of movies which contain a movieID,Movie Name, and genre. 我目前有电影的txt文件,其中包含movieID,电影名称和类型。 Example: 例:

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

I am trying to import this file into a SQLite3 table created with Python: 我正在尝试将此文件导入到使用Python创建的SQLite3表中:

import sqlite3

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

Drop Tables 删除表

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

Create Table for Movies 为电影创建表

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()

What's the best way to import my text file into this database with the delimiter being ','? 将分隔符为','的文本文件导入此数据库的最佳方法是什么?

You can read in the txt file and split on , : 你可以在阅读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)

I would have used python csv module to do that: 我本来可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM