目录

file.readline([size])

描述 (Description)

readline()方法从文件中读取整行。 尾随换行符保留在字符串中。 如果size参数存在且非负数,则它是包含尾随换行符的最大字节数,并且可能返回不完整的行。

仅在立即遇到EOF时才返回空字符串。

语法 (Syntax)

以下是readline()方法的语法 -

fileObject.readline( size );

参数 (Parameters)

  • size - 这是从文件中读取的字节数。

返回值 (Return Value)

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

例子 (Example)

以下示例显示了readline()方法的用法。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print "Read Line: %s" % (line)
line = fo.readline(5)
print "Read Line: %s" % (line)
# Close opend file
fo.close()

当我们运行上面的程序时,它产生以下结果 -

Name of the file:  foo.txt
Read Line: Python is a great language.
Read Line: Yeah 
↑回到顶部↑
WIKI教程 @2018