Python 檔案 readlines() 方法



Python 檔案 readlines() 方法一次性讀取檔案中的所有行。這意味著,檔案會連續讀取,直到遇到檔案結尾 (EOF)。這可以透過內部使用 readline() 方法實現。

此方法僅適用於較小的檔案,因為檔案內容會被讀取到記憶體中,然後將各行分割成單獨的行。readlines() 方法還接受一個可選引數,我們可以用來限制要讀取的位元組數。

只有當立即遇到 EOF 時,才會返回空字串。

語法

以下是 Python 檔案 readlines() 方法的語法:

fileObject.readlines(sizehint);

引數

  • sizehint - 這是要從檔案中讀取的位元組數。

返回值

此方法返回一個包含各行的列表。

示例

讓我們使用現有的檔案“foo.txt”來使用 readlines() 方法讀取其中的行。foo.txt 檔案的內容如下:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例演示了 Python 檔案 readlines() 方法的用法。

# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readlines()
print("Read Line: ", line)

# Close opened file
fo.close()

執行上述程式時,會產生以下結果:

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']

示例

但是,如果我們將某些值作為可選引數 *sizehint* 傳遞,此方法只會讀取最多指定的位元組數,並在末尾附加換行符。但是,如果引數小於第一行的長度,則該方法仍然會返回完整的第一行。

# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)

# Passing the size argument to the readline() method
line = fo.readlines(2)
print("Read Line:", line)

# Close opened file
fo.close()

如果我們編譯並執行上面的程式,則結果將如下所示:

Name of the file:  foo.txt
Read Line: ['This is 1st line\n']

示例

現在,如果檔案以二進位制讀取模式 (rb) 開啟,此方法將返回二進位制物件。

我們使用 open() 函式以二進位制讀取模式 (rb) 開啟現有的檔案“foo.txt”。在表示此檔案的 file 物件上呼叫 readlines() 方法,以獲取其內容的二進位制形式作為返回值。在這種情況下,如果引數小於第一行的長度,則該方法將返回空列表。

# Open a file
fo = open("foo.txt", "rb")
print("Name of the file: ", fo.name)

line = fo.readlines()
print("Read Line:", line)

# Passing the optional parameter
line = fo.readlines(3)
print("Read Line:", line)

# Close opened file
fo.close()

程式編譯並執行後,輸出將顯示如下:

Name of the file:  foo.txt
Read Line: [b'This is 1st line\r\n', b'This is 2nd line\r\n', b'This is 3rd line\r\n', b'This is 4th line\r\n', b'This is 5th line']
Read Line: []

示例

即使 size 引數大於當前檔案內容的長度,此方法仍然會返回檔案中的所有行。

# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)

line = fo.readlines(120)
print("Read Line:", line)

# Close opened file
fo.close()

讓我們編譯並執行給定的程式,輸出將顯示如下:

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
python_file_methods.htm
廣告