File函数 中的 file.readline([size])

首页 / Python2入门教程 / File函数 中的 file.readline([size])

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

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

链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-readline.html

来源:LearnFk无涯教程网

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 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

趣谈网络协议 -〔刘超〕

从0开发一款iOS App -〔朱德权〕

跟着高手学复盘 -〔张鹏〕

手把手带你写一门编程语言 -〔宫文学〕

攻克视频技术 -〔李江〕

搞定音频技术 -〔冯建元 〕

高并发系统实战课 -〔徐长龙〕

结构执行力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)