Python的readlines(n)函数行为

15

我已经阅读了文档,但是readlines(n)是什么意思?在这里,readlines(n)指的是readlines(3)或者其他数字。

当我运行readlines(3)时,它返回与readlines()相同的结果。

3个回答

17

可选参数应该表示从文件中读取多少(大约)字节。文件将继续被读取,直到当前行结束:

readlines([size]) -> list of strings, each a line from the file.

Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.

另外一句话:

如果给定一个可选的参数sizehint,它会从文件中读取那么多字节以及足够补全一行的字节,然后返回从中得到的行。

你说它似乎对于小文件没有什么作用,这很有趣:

In [1]: open('hello').readlines()
Out[1]: ['Hello\n', 'there\n', '!\n']

In [2]: open('hello').readlines(2)
Out[2]: ['Hello\n', 'there\n', '!\n']

有人可能认为它可以通过文档中以下短语来解释:

使用 readline() 读取直到 EOF,并返回包含已读取行的列表。 如果存在可选的 sizehint 参数,而不是读取到 EOF,将读取大约总共大小为sizehint字节的整行(可能会向内部缓冲区大小四舍五入)。 实现类似文件接口的对象可以选择忽略 sizehint,如果无法实现或无法高效实现,则可以忽略。

然而,即使我尝试不使用缓冲区读取文件,它似乎也没有改变任何东西,这意味着指的是某种其他类型的内部缓冲区:

In [4]: open('hello', 'r', 0).readlines(2)
Out[4]: ['Hello\n', 'there\n', '!\n']
在我的系统中,这个内部缓冲区大小似乎约为5k字节/1.7k行:
In [1]: len(open('hello', 'r', 0).readlines(5))
Out[1]: 1756

In [2]: len(open('hello', 'r', 0).readlines())
Out[2]: 28080

3
我很乐意为您翻译,但我认为在这里使用其他语言不是一个好主意。 - Lev Levitsky
@user2013613 是的,只要文件大小小于这个“内部缓冲区”,它就不会执行任何操作。 - Lev Levitsky

1
它列出了给定字符大小'n'所跨越的行,从当前行开始。 例如:在一个文本文件中,内容为
one
two
three
four

open('text').readlines(0) 返回 ['one\n', 'two\n', 'three\n', 'four\n']

open('text').readlines(1) 返回 ['one\n']

open('text').readlines(3) 返回 ['one\n']

open('text').readlines(4) 返回 ['one\n', 'two\n']

open('text').readlines(7) 返回 ['one\n', 'two\n']

open('text').readlines(8) 返回 ['one\n', 'two\n', 'three\n']

open('text').readlines(100) 返回 ['one\n', 'two\n', 'three\n', 'four\n']


1
根据文件大小,readlines(hint)应返回一组较小的行。文档中说明如下:
f.readlines() returns a list containing all the lines of data in the file. 
If given an optional parameter sizehint, it reads that many bytes from the file 
and enough more to complete a line, and returns the lines from that. 
This is often used to allow efficient reading of a large file by lines, 
but without having to load the entire file in memory. Only complete lines 
will be returned.

因此,如果您的文件有数千行,您可以传入例如... 65536,并且它只会每次读取那么多字节加上足够完成下一行的内容,返回所有完全读取的行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接