Python3 file.readlines()方法

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文件方法