【轉自: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'>>>