Python 3 - 文件 readlines() 方法

  • 描述

    方法readlines()使用 readline() 读取直到 EOF 并返回包含行的列表。如果存在可选的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: