首页 > Python资料 博客日记

Python文件readline()方法

2023-08-04 16:44:00Python资料围观171

本篇文章分享Python文件readline()方法,对你有帮助的话记得收藏一下,看Python资料网收获更多编程知识

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

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

语法

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

fileObject.readline( size );

参数

  • size − 这是要从文件读取的字节数。

返回值

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

示例

假设’foo.txt‘文件中包含以下行 -

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

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

#!/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

版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐