Python檔readline()方法

Python檔的readline()方法從檔中讀取一行。字串中保留一個尾隨的換行字元。 如果size參數存在且非負數,則它是包含尾隨換行符的最大字節數,並且可能返回不完整的行。

僅在遇到EOF時才返回空字元串。

語法

以下是readline()方法的語法 -

fileObject.readline( size );

參數

  • size − 這是要從檔讀取的位元組數。

返回值

  • 該方法返回從檔讀取的行。

示例

假設’foo.txt‘檔中包含以下行 -

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

以下示例顯示了readline()方法的用法。

#!/usr/bin/python3

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

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

line = fo.readline(5)
print ("Read Line: %s" % (line))

# Close opened file
fo.close()

執行上面代碼後,將得到以下結果 -

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

Read Line: This

上一篇: Python檔對象方法 下一篇: Python os模組方法