Python實(shí)現(xiàn)讀取TXT文件數(shù)據(jù)并存進(jìn)內(nèi)置數(shù)據(jù)庫(kù)SQLite3的方法
本文實(shí)例講述了Python實(shí)現(xiàn)讀取TXT文件數(shù)據(jù)并存進(jìn)內(nèi)置數(shù)據(jù)庫(kù)SQLite3的方法。分享給大家供大家參考,具體如下:
當(dāng)TXT文件太大,計(jì)算機(jī)內(nèi)存不夠時(shí),我們可以選擇按行讀取TXT文件,并將其存儲(chǔ)進(jìn)Python內(nèi)置輕量級(jí)splite數(shù)據(jù)庫(kù),這樣可以加快數(shù)據(jù)的讀取速度,當(dāng)我們需要重復(fù)讀取數(shù)據(jù)時(shí),這樣的速度加快所帶來(lái)的時(shí)間節(jié)省是非??捎^(guān)的,比如,當(dāng)我們?cè)谟?xùn)練數(shù)據(jù)時(shí),要迭代10萬(wàn)次,即要從文件中讀取10萬(wàn)次,即使每次只加快0.1秒,那么也能節(jié)省幾個(gè)小時(shí)的時(shí)間了。
#創(chuàng)建數(shù)據(jù)庫(kù)并把txt文件的數(shù)據(jù)存進(jìn)數(shù)據(jù)庫(kù) import sqlite3 #導(dǎo)入sqlite3 cx = sqlite3.connect('./train.db') #創(chuàng)建數(shù)據(jù)庫(kù),如果數(shù)據(jù)庫(kù)已經(jīng)存在,則鏈接數(shù)據(jù)庫(kù);如果數(shù)據(jù)庫(kù)不存在,則先創(chuàng)建數(shù)據(jù)庫(kù),再鏈接該數(shù)據(jù)庫(kù)。 cu = cx.cursor() #定義一個(gè)游標(biāo),以便獲得查詢(xún)對(duì)象。 cu.execute('create table if not exists train4 (id integer primary key,name text)') #創(chuàng)建表 fr = open('data_sample.txt') #打開(kāi)要讀取的txt文件 i = 0 for line in fr.readlines(): #將數(shù)據(jù)按行插入數(shù)據(jù)庫(kù)的表train4中。 cu.execute('insert into train4 values(?,?)',(i,line)) i +=1 cu.close() #關(guān)閉游標(biāo) cx.commit() #事務(wù)提交 cx.close() #關(guān)閉數(shù)據(jù)庫(kù)
查詢(xún)數(shù)據(jù):
cu.execute('select * from train4 where id = ?',(i,)) #i代表你要讀取表train4中某一行的數(shù)據(jù) result = cu.fetchall()
注:如果前面已經(jīng)關(guān)閉了數(shù)據(jù)庫(kù),那么在查詢(xún)時(shí)要重新打開(kāi)數(shù)據(jù)庫(kù),并創(chuàng)建游標(biāo)。這一點(diǎn)要注意一下。
完整的查詢(xún)程序是這樣的:
import sqlite3 cx = sqlite3.connect('./train.db') cu = cx.cursor() for i in range(5): cu.execute('select * from train4 where id = ?',(i,)) result = cu.fetchall() cx.commit() cu.close() cx.close()
另:這里再為大家附帶一個(gè)SQLite3數(shù)據(jù)操作類(lèi)供大家參考使用:
import sqlite3 # *************************************************** # * # * Description: Python操作SQLite3數(shù)據(jù)庫(kù)輔助類(lèi)(查詢(xún)構(gòu)造器) # * Author: wangye # * # *************************************************** def _wrap_value(value): return repr(value) def _wrap_values(values): return list(map(_wrap_value, values)) def _wrap_fields(fields): for key,value in fields.items(): fields[key] = _wrap_value(value) return fields def _concat_keys(keys): return "[" + "],[".join(keys) + "]" def _concat_values(values): return ",".join(values) def _concat_fields(fields, operator = (None, ",")): if operator: unit_operator, group_operator = operator # fields = _wrap_fields(fields) compiled = [] for key,value in fields.items(): compiled.append("[" + key + "]") if unit_operator: compiled.append(unit_operator) compiled.append(value) compiled.append(group_operator) compiled.pop() # pop last group_operator return " ".join(compiled) class DataCondition(object): """ 本類(lèi)用于操作SQL構(gòu)造器輔助類(lèi)的條件語(yǔ)句部分 例如: DataCondition(("=", "AND"), id = 26) DataCondition(("=", "AND"), True, id = 26) """ def __init__(self, operator = ("=", "AND"), ingroup = True, **kwargs): """ 構(gòu)造方法 參數(shù): operator 操作符,分為(表達(dá)式操作符, 條件運(yùn)算符) ingroup 是否分組,如果分組,將以括號(hào)包含 kwargs 鍵值元組,包含數(shù)據(jù)庫(kù)表的列名以及值 注意這里的等于號(hào)不等于實(shí)際生成SQL語(yǔ)句符號(hào) 實(shí)際符號(hào)是由operator[0]控制的 例如: DataCondition(("=", "AND"), id = 26) (id=26) DataCondition((">", "OR"), id = 26, age = 35) (id>26 OR age>35) DataCondition(("LIKE", "OR"), False, name = "John", company = "Google") name LIKE 'John' OR company LIKE "Google" """ self.ingroup = ingroup self.fields = kwargs self.operator = operator def __unicode__(self): self.fields = _wrap_fields(self.fields) result = _concat_fields(self.fields, self.operator) if self.ingroup: return "(" + result + ")" return result def __str__(self): return self.__unicode__() def toString(self): return self.__unicode__() class DataHelper(object): """ SQLite3 數(shù)據(jù)查詢(xún)輔助類(lèi) """ def __init__(self, filename): """ 構(gòu)造方法 參數(shù): filename 為SQLite3 數(shù)據(jù)庫(kù)文件名 """ self.file_name = filename def open(self): """ 打開(kāi)數(shù)據(jù)庫(kù)并設(shè)置游標(biāo) """ self.connection = sqlite3.connect(self.file_name) self.cursor = self.connection.cursor() return self def close(self): """ 關(guān)閉數(shù)據(jù)庫(kù),注意若不顯式調(diào)用此方法, 在類(lèi)被回收時(shí)也會(huì)嘗試調(diào)用 """ if hasattr(self, "connection") and self.connection: self.connection.close() def __del__(self): """ 析構(gòu)方法,做一些清理工作 """ self.close() def commit(self): """ 提交事務(wù) SELECT語(yǔ)句不需要此操作,默認(rèn)的execute方法的 commit_at_once設(shè)為T(mén)rue會(huì)隱式調(diào)用此方法, 否則就需要顯示調(diào)用本方法。 """ self.connection.commit() def execute(self, sql = None, commit_at_once = True): """ 執(zhí)行SQL語(yǔ)句 參數(shù): sql 要執(zhí)行的SQL語(yǔ)句,若為None,則調(diào)用構(gòu)造器生成的SQL語(yǔ)句。 commit_at_once 是否立即提交事務(wù),如果不立即提交, 對(duì)于非查詢(xún)操作,則需要調(diào)用commit顯式提交。 """ if not sql: sql = self.sql self.cursor.execute(sql) if commit_at_once: self.commit() def fetchone(self, sql = None): """ 取一條記錄 """ self.execute(sql, False) return self.cursor.fetchone() def fetchall(self, sql = None): """ 取所有記錄 """ self.execute(sql, False) return self.cursor.fetchall() def __concat_keys(self, keys): return _concat_keys(keys) def __concat_values(self, values): return _concat_values(values) def table(self, *args): """ 設(shè)置查詢(xún)的表,多個(gè)表名用逗號(hào)分隔 """ self.tables = args self.tables_snippet = self.__concat_keys(self.tables) return self def __wrap_value(self, value): return _wrap_value(value) def __wrap_values(self, values): return _wrap_values(values) def __wrap_fields(self, fields): return _wrap_fields(fields) def __where(self): # self.condition_snippet if hasattr(self, "condition_snippet"): self.where_snippet = " WHERE " + self.condition_snippet def __select(self): template = "SELECT %(keys)s FROM %(tables)s" body_snippet_fields = { "tables" : self.tables_snippet, "keys" : self.__concat_keys(self.body_keys), } self.sql = template % body_snippet_fields def __insert(self): template = "INSERT INTO %(tables)s (%(keys)s) VALUES (%(values)s)" body_snippet_fields = { "tables" : self.tables_snippet, "keys" : self.__concat_keys(list(self.body_fields.keys())), "values" : self.__concat_values(list(self.body_fields.values())) } self.sql = template % body_snippet_fields def __update(self): template = "UPDATE %(tables)s SET %(fields)s" body_snippet_fields = { "tables" : self.tables_snippet, "fields" : _concat_fields(self.body_fields, ("=",",")) } self.sql = template % body_snippet_fields def __delete(self): template = "DELETE FROM %(tables)s" body_snippet_fields = { "tables" : self.tables_snippet } self.sql = template % body_snippet_fields def __build(self): { "SELECT": self.__select, "INSERT": self.__insert, "UPDATE": self.__update, "DELETE": self.__delete }[self.current_token]() def __unicode__(self): return self.sql def __str__(self): return self.__unicode__() def select(self, *args): self.current_token = "SELECT" self.body_keys = args self.__build() return self def insert(self, **kwargs): self.current_token = "INSERT" self.body_fields = self.__wrap_fields(kwargs) self.__build() return self def update(self, **kwargs): self.current_token = "UPDATE" self.body_fields = self.__wrap_fields(kwargs) self.__build() return self def delete(self, *conditions): self.current_token = "DELETE" self.__build() #if *conditions: self.where(*conditions) return self def where(self, *conditions): conditions = list(map(str, conditions)) self.condition_snippet = " AND ".join(conditions) self.__where() if hasattr(self, "where_snippet"): self.sql += self.where_snippet return self
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python操作SQLite數(shù)據(jù)庫(kù)技巧總結(jié)》、《Python常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python基于Logistic回歸建模計(jì)算某銀行在降低貸款拖欠率的數(shù)據(jù)示例
這篇文章主要介紹了Python基于Logistic回歸建模計(jì)算某銀行在降低貸款拖欠率的數(shù)據(jù),結(jié)合實(shí)例形式分析了Python基于邏輯回歸模型的數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-01-01pytorch之torch_scatter.scatter_max()用法
這篇文章主要介紹了pytorch之torch_scatter.scatter_max()用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09Pyqt5實(shí)戰(zhàn)小案例之界面與邏輯分離的小計(jì)算器程序
網(wǎng)上很多PyQt5信號(hào)槽與界面分離的例子,但是真正開(kāi)發(fā)起來(lái)很不方便,下面這篇文章主要給大家介紹了關(guān)于Pyqt5實(shí)戰(zhàn)小案例之界面與邏輯分離的小計(jì)算器程序,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02Python實(shí)現(xiàn)的tcp端口檢測(cè)操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)的tcp端口檢測(cè)操作,結(jié)合實(shí)例形式分析了Python使用socket模塊實(shí)現(xiàn)tcp端口檢測(cè)功能的相關(guān)操作技巧,需要的朋友可以參考下2018-07-07python ftfy庫(kù)處理金融方面文件編碼錯(cuò)誤實(shí)例詳解
這篇文章主要為大家介紹了使用python ftfy庫(kù)處理金融方面文件編碼錯(cuò)誤實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01python 創(chuàng)建彈出式菜單的實(shí)現(xiàn)代碼
這篇文章主要介紹了python 創(chuàng)建彈出式菜單的實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-07-07