python - 管理 .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
我如何管理变量“内容”中的数据,以将其存储在数据库中,并用表格分隔为等级、姓名和性别。
解决方案
如果您坚持从文本文件手动插入数据,或者您不知道有哪些分隔符,您可以执行以下操作:
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()
推荐阅读
- java - 如何在经典(非引导)Spring 应用程序中注册 MessageDispatcherServlet
- vb.net - PostgreSQL:VB.NET ODBC 更新无法正常工作
- regex - 正则表达式 - 找出包含一个单词或其子字符串后不跟某个字符的字符串
- swift - 如何在 macOS 中获取实时麦克风输入?
- bash - systemctl service systemd-notify 不适用于非 root 用户
- excel - 我想获取“另存为”菜单中列出的“当前文件夹”
- vue.js - 从 [__ob__: Observer] 中提取数据
- javascript - 我的列表项不会在单击按钮时删除
- swift - 'Box' 要求 'CanFly' 是类类型
- javascript - 如何在 webpack 4 中使用 vuejs 作为 UMD?