本文介绍了Python 的函数 readlines(n) 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读文档,但是 readlines(n) 有什么作用呢?readlines(n) 是指 readlines(3) 或任何其他数字.

I've read the documentation, but what does readlines(n) do? By readlines(n), I mean readlines(3) or any other number.

当我运行 readlines(3) 时,它返回与 readlines() 相同的内容.

When I run readlines(3), it returns same thing as readlines().

推荐答案

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

The optional argument should mean how many (approximately) bytes are read from the file. The file will be read further, until the current line ends:

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,它会从文件中读取那么多字节和足够多的字节来完成一行,并从中返回行.

您说得对,它似乎对小文件没有太大作用,这很有趣:

You're right that it doesn't seem to do much for small files, which is interesting:

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']

人们可能认为文档中的以下短语对此进行了解释:

One might think it's explained by the following phrase in the documentation:

使用 readline() 读取直到 EOF 并返回包含所读取行的列表.如果存在可选的 sizehint 参数,则不会读取到 EOF,而是读取总计大约 sizehint 字节(可能在向上舍入到内部缓冲区大小之后)的整行.实现类文件接口的对象可能会选择忽略 sizehint,如果它无法实现,或者无法有效实现.

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

However, even when I try to read the file without buffering, it doesn't seem to change anything, which means some other kind of internal buffer is meant:

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

在我的系统上,这个内部缓冲区大小似乎约为 5k 字节/1.7k 行:

On my system, this internal buffer size seems to be around 5k bytes / 1.7k lines:

In [1]: len(open('hello', 'r', 0).readlines(5))
Out[1]: 1756

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

这篇关于Python 的函数 readlines(n) 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:50