Python3 file.readlines()方法

2019-10-16 23:09:43
readlines()方法讀取直到EOF,使用 readline()並返回包含行的列表。如果可選 sizehint 引數存在就不讀取到EOF,全行共計約sizehint位元組(四捨五入到內部緩衝區大小後)被讀取。
當遇到EOF,一個空字串被返回。

語法

下面是 readlines()方法的語法方法 -
fileObject.readlines( sizehint );

引數

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

返回值

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

範例

下面的例子顯示 readlines()方法的使用。
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3

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

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

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

# Close opened file
fo.close()
當我們執行上面的程式,會產生以下結果 -
Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 
            'This is 3rd line\n', 'This is 4th line\n', 
            'This is 5th line\n']
Read Line: