位置:首頁 > 腳本語言 > Python教學 > Python file.readline()方法

Python file.readline()方法

readline()方法從文件中讀取一整行。尾部的換行符保持在字符串中。如果大小參數且非負,那麼一個最大字節數,包括結尾的換行和不完整的行可能會返回。

遇到EOF時立即返回一個空字符串。

語法

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

fileObject.readline( size );

參數

  • size -- 這是可以從文件中讀取的字節數。

返回值

此方法返回從文件中讀取的行。

例子

下麵的例子顯示了readline()方法的使用。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
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: %s" % (line)

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

# Close opend file
fo.close()

當我們運行上麵的程序,它會產生以下結果:

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

Read Line: This