Python讀取文件內(nèi)容的三種常用方式及效率比較
本文實例講述了Python讀取文件內(nèi)容的三種常用方式。分享給大家供大家參考,具體如下:
本次實驗的文件是一個60M的文件,共計392660行內(nèi)容。

程序一:
def one():
start = time.clock()
fo = open(file,'r')
fc = fo.readlines()
num = 0
for l in fc:
tup = l.rstrip('\n').rstrip().split('\t')
num = num+1
fo.close()
end = time.clock()
print end-start
print num
運行結果:0.812143868027s
程序二:
def two():
start = time.clock()
num = 0
with open(file, 'r') as f:
for l in f:
tup = l.rstrip('\n').rstrip().split('\t')
num = num+1
end = time.clock()
times = (end-start)
print times
print num
運行時間:0.74222778078
程序三:
def three():
start = time.clock()
fo = open(file,'r')
l = fo.readline()
num = 0
while l:
tup = l.rstrip('\n').rstrip().split('\t')
l = fo.readline()
num = num+1
end = time.clock()
print end-start
print num
運行時間:1.02316120797
由結果可得出,程序二的速度最快。
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
理解Python數(shù)據(jù)離散化手寫if-elif語句與pandas中cut()方法實現(xiàn)
這篇文章主要介紹了通過手寫if-elif語句與pandas中cut()方法實現(xiàn)示例理解Python數(shù)據(jù)離散化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
python 使用matplotlib 實現(xiàn)從文件中讀取x,y坐標的可視化方法
今天小編就為大家分享一篇python 使用matplotlib 實現(xiàn)從文件中讀取x,y坐標的可視化方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python+Tkinter創(chuàng)建一個簡單的鬧鐘程序
這篇文章主要為大家詳細介紹了如何使用 Python 的 Tkinter 庫創(chuàng)建一個簡單的鬧鐘程序,它可以在指定的時間播放一個聲音來提醒你,感興趣的可以學習一下2023-04-04

