1:readline()測試
file = open("sample.txt") while 1: line = file.readline() if not line: break pass # do something
file.close()
一行一行得從文件讀數據,顯然比較慢;spa
不過很省內存;code
測試讀10M的sample.txt文件,每秒大約讀32000行;blog
2:fileinput內存
import fileinput for line in fileinput.input("sample.txt"): pass
寫法簡單一些,不過測試之後發現每秒只能讀13000行數據,效率比上一種方法慢了兩倍多;input
3:readlines()it
file = open("sample.txt") while 1: lines = file.readlines(100000) if not lines: break for line in lines: pass # do something
file.close()
用一樣的數據測試,它每秒能夠讀96900行數據!效率是第一種方法的3倍,第二種方法的7倍!class
4:文件迭代器效率
每次只讀取和顯示一行,讀取大文件時應該這樣:import
file = open("sample.txt") for line in file: pass # do something
file.close()