欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python從數(shù)據(jù)庫(kù)讀取大量數(shù)據(jù)批量寫(xiě)入文件的方法

 更新時(shí)間:2018年12月10日 11:11:30   作者:DiamondTan  
今天小編就為大家分享一篇Python從數(shù)據(jù)庫(kù)讀取大量數(shù)據(jù)批量寫(xiě)入文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

使用機(jī)器學(xué)習(xí)訓(xùn)練數(shù)據(jù)時(shí),如果數(shù)據(jù)量較大可能我們不能夠一次性將數(shù)據(jù)加載進(jìn)內(nèi)存,這時(shí)我們需要將數(shù)據(jù)進(jìn)行預(yù)處理,分批次加載進(jìn)內(nèi)存。

下面是代碼作用是將數(shù)據(jù)從數(shù)據(jù)庫(kù)讀取出來(lái)分批次寫(xiě)入txt文本文件,方便我們做數(shù)據(jù)的預(yù)處理和訓(xùn)練機(jī)器學(xué)習(xí)模型。

#%%
import pymssql as MySQLdb #這里是python3 如果你是python2.x的話,import MySQLdb
#數(shù)據(jù)庫(kù)連接屬性
hst = '188.10.34.18'
usr = 'sa'
passwd = 'p@ssw0rd'
db = 'HistoryTrace'
 
#總共多少數(shù)據(jù)
allData = 1674333
#每個(gè)批次多少條數(shù)據(jù)
dataOfEach = 20000
#批次
batch = ceil(allData/dataOfEach)
 
#文件名
global IDctrl 
IDctrl = 1
filename = str(IDctrl)+'.txt'
 
#連接數(shù)據(jù)庫(kù)
conn = MySQLdb.connect(host=hst,user=usr,password=passwd,database=db)
cur=conn.cursor()
 
while IDctrl<batch:
 #讀取數(shù)據(jù)庫(kù)
 sql = 'SELECT Longitude,Latitude,Altitude,VelComOfLong,VelComOfLati,Aircraft,Section,TimeMinus\
    FROM dealed1 where ID>=' + str(IDctrl) + ' and ID <' + str(IDctrl + dataOfEach) 
 cur.execute(sql)
 rows=cur.fetchall()
 #寫(xiě)文件
 f = open(filename,'w')
 f.writelines(str(rows))
 #文件名加1
 IDctrl+=1
 filename = str(IDctrl)+'.txt'
 
#關(guān)閉數(shù)據(jù)庫(kù)連接
f.close()
conn.close()

以上這篇Python從數(shù)據(jù)庫(kù)讀取大量數(shù)據(jù)批量寫(xiě)入文件的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論