【问题标题】:Python program, inserting txt file to sqlite3 databasePython程序,将txt文件插入sqlite3数据库
【发布时间】: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


【解决方案1】:

假设您有一个名为 kernel.txt 的文件,其中包含

Kernel version:            Windows 10 Enterprise, Multiprocessor Free
Product type:              Professional
Product version:           6.3
Service pack:              0

您的 python 代码只需读取该文本文件并将数据插入 SQLite,如下所示:

import sqlite3
conn = sqlite3.connect('systeminfo.db')
c = conn.cursor()

def create_table():
    # same thing you had...just removing it for brevity

def insert_data(filename):

    # read all the lines of the file
    with open(filename) as f:
        file_data = f.readlines()

    # if Kernel version exists in the line, split the line by :
    # take the 2nd item from the split and split it again by ,
    # take the first item and pass it to the insert query
    # don't forget to commit changes
    for item in file_data:
        if 'Kernel version' in item:
            info = item.strip().split(':')
            val = info[1].strip().split(',')
            c.execute(
                'insert into system_information (Kernel_version) values(?)',
                (val[0].strip(),)
            )
            conn.commit()

create_table()
insert_data('kernel.txt')

如果您有多个包含此类信息的文件,或者如果您有一个包含多个类似信息块的文件,则必须更改此代码。不过,此代码将帮助您入门。

更新

我已将数据解析分离为可以多次调用的自己的函数。请注意我是如何创建 3 个变量来存储产品类型和版本等附加信息的。 insert 执行发生在循环之外。基本上,我们是在收集我们需要的所有信息,然后一次性插入。

import sqlite3
conn = sqlite3.connect('systeminfo.db')
c = conn.cursor()

def create_table():
    # same thing you had...just removing it for brevity
    pass

def get_value(item):
    info = item.strip().split(':')
    val = info[1].strip().split(',')
    return val[0].strip()

def insert_data(filename):

    # read all the lines of the file
    with open(filename) as f:
        file_data = f.readlines()

    # if Kernel version exists in the line, split the line by :
    # take the 2nd item from the split and split it again by ,
    # take the first item and pass it to the insert query
    # don't forget to commit changes
    kernel_version = ''
    product_type = ''
    product_version = ''

    for item in file_data:
        if 'Kernel version' in item:
            kernel_version = get_value(item)
        elif 'Product type' in item:
            product_type = get_value(item)
        elif 'Product version' in item:
            product_version = get_value(item)

    c.execute(
        '''insert into system_information
        (Kernel_version, Product_type, Product_version)
        values(?, ?, ?)''',
        (kernel_version, product_type, product_version,)
    )
    conn.commit()

create_table()
insert_data('kernel.txt')

【讨论】:

  • 这绝对帮助我朝着正确的方向前进!现在我该如何插入下一行?哪些语句将帮助我继续写入数据库?可以举个例子吗,拜托!很大的帮助!到现在为止还挺好!明白这一点!
  • 更新了我在帖子中尝试的内容。
  • @olorid 下一行是什么意思?您想在 product_type 中输入产品类型,在 product_version 字段中输入产品版本?
  • 是的!如何在 if 语句之后继续将下一行的更多信息(如产品类型)输入到 sqlite 中的 product_version 中,我正在使用 elif 语句,不确定我是否这样做正确,因为我收到错误,或者我如何能做到这一点.
  • 很高兴听到您尝试了几件事。很好。不在这个问题中,而是在未来的问题中,请随时用您尝试过的东西更新问题。它向观众展示了您如何集中精力。希望这个例子能让你继续前进。一旦您满意,您可以通过等待其他答案或将其中一个答案标记为已接受来关闭您的票证。
猜你喜欢
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多