標籤:python read readline readlines
python讀取檔案內容時,有三種方法:read()、readline()和readlines()
這三種方法區別如下:
read(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
簡單說,read()方法若不指定讀取位元組數,預設讀取全部檔案內容(所有檔案內容存在記憶體),產生一個字串。
readline(...) readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.
簡單說,readline()方法若不指定讀取的位元組數,預設每次讀取一行,產生一個字串。每執行一次readline()方法,則讀取檔案的一行。可用迴圈來完成整個檔案的讀取。
readlines(...) readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
簡單說,readlines()方法若不指定讀取的位元組數,預設讀取整個檔案內容(所有檔案內容存在記憶體),產生一個列表。列表中的每個元素是檔案的一行。可用for迴圈列印沒一行。
註:對於很大的檔案,不適合使用read()和readlines()方法。因為這兩種方法都是一次性將檔案內容讀取完放入記憶體。
python 點滴記錄8:檔案操作read、readline與readlines