【发布时间】:2019-04-24 14:45:45
【问题描述】:
目前正在使用 Python 编写一个程序,该程序必须从文本文件中获取数据并将其输入到 SQLite 中的适当位置。我已经创建了我的数据库和列,现在我被困在如何处理文本数据并将其读入 sqlite 数据库中。
这里有几行来自文本文件。
Kernel version: Windows 10 Enterprise, Multiprocessor Free
Product type: Professional
Product version: 6.3
Service pack: 0
这是我目前所拥有的,
import sqlite3
conn = sqlite3.connect('systeminfo.db')
c = conn.cursor()
def create_table():
c.execute("""CREATE TABLE IF NOT EXISTS system_information (
Machine_Name text,
Kernel_version text,
Product_type text,
product_version text,
Registered_organization text,
registered_owner text,
system_root text,
processors text,
physical_memory text
)""")
create_table1()
这将按照我想要的方式创建我的数据库和表,现在我坚持从文本文件中获取例如内核版本并将“Windows 10 Enterprise”放入 Kernel_Version 列下的数据库中。
更新:
使用@zedfoxus 提示后,我能够成功获取数据,这就是我所拥有的,现在我怎样才能更高效地执行下一行?我正在使用 elif,出现错误,
def insert_data(psinfo):
with open(psinfo) as f:
file_data = f.readlines()
for item in file_data:
if 'Kernel version' in item:
info = item.strip().split(':')
val = info[1].strip().split(',')
elif 'Product type' in item:
info = item.strip().split(':')
val = info[1].strip().split(',')
c.execute(
'INSERT INTO system_information (Kernel_version,Product_type ) values(?,?)',
(val[1].strip(),)
)
conn.commit()
【问题讨论】:
-
您的问题对我来说似乎有点宽泛,因为您想要做的事情涉及几个步骤,并且可能有几种不同的方式可以实现您想要的。但基本上你想要做的事情有三个步骤:读取文件的行,处理每一行以提取你想要的文本,并将提取的文本插入数据库。您是否遇到了某个特定步骤?
-
现在这就是我如何使用@zedfoxus 并为多行执行此操作,例如什么语句以及如何使用它?他做了 kernel_version,现在什么语句最好做下一行,例如 Product_type?
-
更新了我在帖子中尝试的内容
标签: python-3.x database text sqlite