轉載 python每次讀入檔案一行的問題(血的教訓啊)

來源:互聯網
上載者:User
 http://blog.csdn.net/oldjwu/article/details/4329401
Python每次讀入檔案一行的問題分類: Python2009-07-07 21:46 1612人閱讀 評論(0) 收藏 舉報

  注意到Python每次讀入一個檔案的一行時,可以有兩種寫法:

 

 

[python] view plaincopy
  1. f = open("bigFile.txt", "r")  
  2. while True:  
  3.     line = f.readline()  
  4.     if line:  
  5.         pass    # do something here  
  6.     else:  
  7.         break  
  8. f.close()  

 

 

   另一種寫法為:

 

 

[python] view plaincopy
  1. f = open("bigFile.txt", "r")  
  2. for line in f:  
  3.     pass    # do something here  
  4. f.close()  

 

 

  很明顯地,後一種寫法更簡潔,而且經過測試,效率似乎也略高一些,不過好像很少看見這樣的寫法。不知道這兩種寫法有什麼區別。

 

 

 

 

 

剛剛看到PyDoc中的FileObject的next()說明
-----------------------------------------
next( )

A file object is its own iterator, for example iter(f) returns f
(unless f is closed). When a file is used as an iterator, typically in
a for loop (for example, for line in f: print line), the next() method
is called repeatedly. This method returns the next input line, or
raises StopIteration when EOF is hit when the file is open for reading
(behavior is undefined when the file is open for writing). In order to
make a for loop the most efficient way of looping over the lines of a
file (a very common operation), the next() method uses a hidden read-
ahead buffer. As a consequence of using a read-ahead buffer, combining
next() with other file methods (like readline()) does not work right.
However, using seek() to reposition the file to an absolute position
will flush the read-ahead buffer. New in version 2.3.

相關文章

聯繫我們

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