Python3 file.readline()方法

readline()方法从文件中读取一个完整的行。结尾的换行符也保持在字符串中。如果参数 size 存在且非负,这是一个最大字节数,包括结尾的换行和不完整的行可能被返回。
当遇到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

上一篇: Python3模块 下一篇: Python3文件方法