熱線電話:13121318867

登錄
首頁精彩閱讀Python讀取文件內容的三種常用方式及效率比較
Python讀取文件內容的三種常用方式及效率比較
2018-02-22
收藏

Python讀取文件內容的三種常用方式及效率比較

本文實例講述了Python讀取文件內容的三種常用方式。分享給大家供大家參考,具體如下:
本次實驗的文件是一個60M的文件,共計392660行內容。
程序一:  
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
由結果可得出,程序二的速度最快。
img

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢