python中readlines函数例子_Python的函数readlines(n)行为

本文探讨了Python中`readlines()`函数的使用,特别是当配合可选参数size时,如何影响文件读取行为。实验表明,size参数对小文件影响不大,但可能揭示了内部缓冲区的存在,如默认缓冲大小约为5k字节。
摘要由CSDN通过智能技术生成

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

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.

另一个引用:

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.

你是对的,它似乎对小文件没有太大作用,这很有趣:

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

有人可能认为文档中的以下短语解释了它:

Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值