首页 > 解决方案 > 管理 .txt 文件中的数据以将其存储到 Python 中的 SQLite3

问题描述

我需要将 .txt 文件中的数据存储到 Sqlite3 中的数据库中。

我首先尝试读取 txt 文件:

f = open("path", 'r')
if f.mode=='r':
    content = f.read()

然后我打印了“内容”以了解数据的结构

print (content)

Rank   Male     Female 
1       Noah    Emma
2       Liam    Olivia
3       William Ava
4       Mason   Sophia
5       James   Isabella

我如何管理变量“内容”中的数据,以将其存储在数据库中,并用表格分隔为等级、姓名和性别。

标签: pythonsqlite

解决方案


如果您坚持从文本文件手动插入数据,或者您不知道有哪些分隔符,您可以执行以下操作:

import sqlite3

# create in-memory db and connect
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2, col3);")  # use your column names here

# read data from file
f = open('<YOUR_FILE.TXT>', 'r')
cont = f.read()
f.close()

# format for inserting to db
rows = cont.split('\n')
rows = rows[1:]  # delete first row with captions
formatted = [tuple(x.split()) for x in rows]

# insert into db
cur.executemany("INSERT INTO t (col1, col2, col3) VALUES (?, ?, ?)", formatted)
con.commit()
con.close()

推荐阅读