无涯教程-File函数 - file.readline([size])

85 阅读1分钟

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

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

file.readline([size]) - 语法

fileObject.readline( size );
  • size  -  这是要从文件中读取的字节数。

file.readline([size]) - 返回值

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

file.readline([size]) - 示例

以下示例显示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: This is 1st line

Read Line: This

参考链接

www.learnfk.com/python/file…