python中read() readline()以及readlines()用法__python

來源:互聯網
上載者:User

【轉自:http://www.ibm.com/developerworks/cn/linux/sdk/python/python-5/index.html#N1004E】

我們談到“文本處理”時,我們通常是指處理的內容。Python 將文字檔的內容讀入可以操作的字串變數非常容易。檔案對象提供了三個“讀”方法: .read()、.readline() 和 .readlines()。每種方法可以接受一個變數以限制每次讀取的資料量,但它們通常不使用變數。 .read() 每次讀取整個檔案,它通常用於將檔案內容放到一個字串變數中。然而 .read() 組建檔案內容最直接的字串表示,但對於連續的面向行的處理,它卻是不必要的,並且如果檔案大於可用記憶體,則不可能實現這種處理。

.readline() 和 .readlines() 非常相似。它們都在類似於以下的結構中使用:

Python .readlines() 樣本

        fh = open('c:\\autoexec.bat')         for  line in  fh.readlines():          print  line

.readline() 和 .readlines() 之間的差異是後者一次讀取整個檔案,象 .read() 一樣。.readlines() 自動將檔案內容分析成一個行的列表,該列表可以由 Python 的 for … in … 結構進行處理。另一方面,.readline() 每次唯讀取一行,通常比 .readlines() 慢得多。僅當沒有足夠記憶體可以一次讀取整個檔案時,才應該使用 .readline()。

python 3中只有unicode str,所以把decode方法去掉了。

Python 2 預設以位元組流(對應 Python 3 的 bytes)的方式讀檔案,不像 Python 3 預設解碼為 unicode。如果檔案內容不是unicode編碼的,要先以二進位方式開啟,讀入位元流,再解碼。

/tmp/ python3Python 3.2.3 (default, Feb 20 2013, 14:44:27) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> f1 = open("unicode.txt", 'r').read()>>> print(f1)寒冷>>> f2 = open("unicode.txt", 'rb').read() #二進位方式開啟>>> print(f2)b'\xe5\xaf\x92\xe5\x86\xb7\n'>>> f2.decode()'寒冷\n'>>> f1.decode()Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'str' object has no attribute 'decode'>>> 

聯繫我們

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