管理.txt文件中的数据以将其存储到Python中的SQLite3
我需要将.txt文件中的数据存储到Sqlite3中的数据库中 我首先尝试读取txt文件:管理.txt文件中的数据以将其存储到Python中的SQLite3,python,sqlite,Python,Sqlite,我需要将.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 Soph
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
如何管理变量“content”中的数据以将其存储在数据库中,数据库中的表以秩、名和性别分隔。如果您坚持手动插入文本文件中的数据,或者您不知道有什么分隔符,可以执行以下操作:
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()
导入sqlite3
#在内存中创建数据库并连接
con=sqlite3.connect(“:内存:”)
cur=con.cursor()
cur.execute(“创建表t(col1,col2,col3);”)#在这里使用列名
#从文件中读取数据
f=打开(“”,'r')
cont=f.read()
f、 关闭()
#插入到数据库的格式
行=继续拆分('\n')
行=行[1:]#删除带有标题的第一行
格式化=[行中x的元组(x.split())]
#插入数据库
cur.executemany(“插入t(col1,col2,col3)值(?,,?)”,格式化)
con.commit()
con.close()
请自己尝试解决这个问题。如果你在网上搜索,有很多指南可供选择。你的代码根本没有使用sqlite3。我被python诅咒了@IvanVinogradov@IvanVinogradov当您打开CSV文件时,它们已经在列表中。TXT文件是严格的CSV TXT文件基本上是相同的格式元组是关键!!