python-3-文件-readline-方法

  • 描述

    方法readline()从文件中读取一整行。尾随的换行符保留在字符串中。如果大小参数存在且非负,则它是最大字节数,包括尾随换行符并且可能返回不完整的行。
    仅当立即遇到 EOF 时才返回空字符串。
  • 句法

    以下是语法readline()方法 -
    
    fileObject.readline( size );
    
  • 参数

    size− 这是要从文件中读取的字节数。
  • 返回值

    此方法返回从文件中读取的行。
  • 例子

    以下示例显示了 readline() 方法的用法。
    
    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.readline()
    print ("Read Line: %s" % (line))
    line = fo.readline(5)
    print ("Read Line: %s" % (line))
    # Close opened file
    fo.close()
    
  • 结果

    当我们运行上面的程序时,它会产生以下结果 -
    
    Name of the file:  foo.txt
    Read Line: This is 1st line
    Read Line: This