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

Python file.readlines()方法

readlines()方法讀取使用ReadLine()並返回包含行的列表直到EOF。如果可選sizehint參數不是讀取到達EOF,全行共計約sizehint字節(可能四舍五入到內部緩衝區的大小後)被讀取。

語法

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

fileObject.readlines( sizehint );

參數

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

返回值

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

例子

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

#!/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.readlines()
print "Read Line: %s" % (line)

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

# Close opend file
fo.close()

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

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