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:
上一篇:
Python3模組
下一篇:
Python3檔方法