Python之路 day2 按行讀檔案

來源:互聯網
上載者:User

標籤:bsp   資料   讀數   記憶體   比較   style   fileinput   input   檔案   

 1 #1. 最基本的讀檔案方法: 2  3 # File: readline-example-1.py 4   5 file = open("sample.txt") 6   7 while 1: 8     line = file.readline() 9     if not line:10         break11     pass # do something12   #一行一行得從檔案讀資料,顯然比較慢;不過很省記憶體。13 14   #在我的機器上讀10M的sample.txt檔案,每秒大約讀32000行15 16 #2. 用fileinput模組17 18 # File: readline-example-2.py19  20 import fileinput21  22 for line in fileinput.input("sample.txt"):23     pass24   #寫法簡單一些,不過測試以後發現每秒只能讀13000行資料,效率比上一種方法慢了兩倍多……25 26 #3. 帶緩衝的檔案讀取27 28 # File: readline-example-3.py29  30 file = open("sample.txt")31  32 while 1:33     lines = file.readlines(100000)34     if not lines:35         break36     for line in lines:37         pass # do something38   #這個方法真的更好嗎?事實證明,用同樣的資料測試,它每秒可以讀96900行資料!效率是第一種方法的3倍,第二種方法的7倍!39 40 ————————————————————————————————————————————————————————————41 42 #在Python 2.2以後,我們可以直接對一個file對象使用for迴圈讀每行資料:43 44 # File: readline-example-5.py45  46 file = open("sample.txt")47  48 for line in file:49     pass # do something50   #而在Python 2.1裡,你只能用xreadlines迭代器來實現:51 52 # File: readline-example-4.py53  54 file = open("sample.txt")55  56 for line in file.xreadlines():57     pass # do something

 

Python之路 day2 按行讀檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.