Python讀大資料txt

來源:互聯網
上載者:User
如果直接對大檔案對象調用 read() 方法,會導致不可預測的記憶體佔用。好的方法是利用固定長度的緩衝區來不斷讀取檔案內容。即通過yield。

在用Python讀一個兩個多G的txt文本時,天真的直接用readlines方法,結果一運行記憶體就崩了。

還好同事點撥了下,用yield方法,測試了下果然毫無壓力。咎其原因,原來是readlines是把常值內容全部放於記憶體中,而yield則是類似於產生器。

代碼如下:

def open_txt(file_name):  with open(file_name,'r+') as f:    while True:      line = f.readline()      if not line:        return      yield line.strip()

調用執行個體:

for text in open_txt('aa.txt'):  print text

例二:

目標 txt 檔案大概有6G,想取出前面1000條資料儲存於一個新的 txt 檔案中做餘下的操作,雖然不知道這樣做有沒有必要但還是先小資料量測試一下吧。參考這個文章:我想把一個list列表儲存到一個Txt文檔,該怎麼儲存 ,自己寫了一個簡單的小程式。
====================================================

import datetimeimport picklestart = datetime.datetime.now()print "start--%s" % (start)fileHandle = open ( 'train.txt' )file2 = open('s_train.txt','w') i = 1while ( i < 10000 ):  a = fileHandle.readline()  file2.write(''.join(a))   i = i + 1fileHandle.close() file2.close()print "done--%s" % ( datetime.datetime.now() - start)if __name__ == '__main__':  pass

====================================================
pickle 這個庫大家說的很多,官網看看,後面可以好好學習一下。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.