Python檔案的readline()
方法從檔案中讀取一行。字串中保留一個尾隨的換行字元。 如果size
引數存在且非負數,則它是包含尾隨換行符的最大位元組數,並且可能返回不完整的行。
僅在遇到EOF時才返回空字串。
語法
以下是readline()
方法的語法 -
fileObject.readline( 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