Python讀取檔案內容的三種方式與效率比較的詳解

來源:互聯網
上載者:User
這篇文章主要介紹了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

由結果可得出,程式二的速度最快。

聯繫我們

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