Python中readlines(n)函数的行为
我看过文档,但是readlines(n)
到底是干嘛的呢?这里的readlines(n)
指的是readlines(3)
或者其他任何数字。
当我运行readlines(3)
的时候,它返回的结果和readlines()
是一样的。
3 个回答
这个功能会列出从当前行开始,给定字符大小'n'所覆盖的行。
举个例子:在一个名为 text
的文件里,内容是
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']
根据文件的大小,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,这样它每次只会读取到这个字节数为止的内容,加上足够的字节来完成下一行,然后返回所有完整读取的行。
可选参数的意思是大约从文件中读取多少字节。文件会继续读取,直到当前行结束:
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() 读取直到文件结束,并返回包含读取行的列表。如果提供了可选的 sizehint 参数,那么就不是读取到文件结束,而是读取总共大约 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