首页 > Python资料 博客日记

Python文件readlines()方法

2023-08-04 15:03:22Python资料围观175

Python资料网推荐Python文件readlines()方法这篇文章给大家,欢迎收藏Python资料网享受知识的乐趣

Python文件的readlines()方法使用readline()读取并返回一个包含行的列表直到EOF。 如果可选的sizehint参数存在,则不读取到EOF,它读取总共大约为sizehint大小的字符串(可能在舍入到内部缓冲区大小之后)的整行。

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

语法

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

fileObject.readlines( sizehint );

参数

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

返回值

  • 此方法返回包含行的列表。

示例

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

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

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

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readlines()
print ("Read Line: %s" % (line))

line = fo.readlines(2)
print ("Read Line: %s" % (line))

# Close opened file
fo.close()

执行上面代码后,将得到以下结果 -

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 
   'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line\n']
Read Line:

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

标签:

相关文章

本站推荐