Python 檔案 readline() 方法



Python 檔案的 readline() 方法從檔案中讀取一行。此方法在讀取行的末尾附加一個尾隨換行符 ('\n')。

readline() 方法還接受一個可選引數,可以在其中指定要從一行讀取的位元組數,包括換行符。預設情況下,此可選引數為 0,因此讀取整行。

僅當立即遇到 EOF 時才返回空字串。

注意

  • 如果檔案以普通讀取模式開啟,則該方法以字串形式返回該行。
  • 如果檔案以二進位制讀取模式開啟,則該方法返回二進位制物件。

語法

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

fileObject.readline(size);

引數

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

返回值

此方法返回從檔案中讀取的行。

示例

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

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

以下示例顯示了在上面提到的演示檔案上使用 readline() 方法。

# 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.readline()
print("Read Line:", line)

# Close opened file
fo.close()

當我們執行以上程式時,它會產生以下結果:

Name of the file: foo.txt
Read Line: This is 1st line 

示例

但是,如果我們將一些值作為可選引數 size 傳遞,則該方法僅讀取最多給定的位元組並在末尾附加換行符。

# 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.readline(5)
print("Read Line:", line)

# Close opened file
fo.close()

如果我們編譯並執行上面的程式,則會產生以下結果:

Name of the file: foo.txt
Read Line: This

示例

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

我們使用 open() 函式以讀取二進位制模式 (rb) 開啟現有的檔案“foo.txt”。readline() 方法在 open() 方法返回的檔案物件上呼叫,以獲取作為檔案行的二進位制形式的返回值。

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

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

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

# Close opened file
fo.close()

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

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

示例

即使 size 引數大於當前檔案中一行的長度,該方法也只返回完整行。

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

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

# Close opened file
fo.close()

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

Name of the file:  foo.txt
Read Line: This is 1st line

python_file_methods.htm
廣告