Python file方法readline()从文件中读取整行。尾随换行符保留在字符串中。如果size参数存在且非负,则它是包括尾随新行的最大字节计数,可能会返回不完整的行。
仅当立即遇到EOF时才返回空字符串。
链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-readline.html
来源:LearnFk无涯教程网
fileObject.readline( size );
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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)