【问题标题】:Python's function readlines(n) behaviorPython 的函数 readlines(n) 行为
【发布时间】:2013-01-26 19:58:51
【问题描述】:

我已经阅读了the documentation,但是 readlines(n) 有什么作用?我所说的 readlines(n) 是指 readlines(3) 或任何其他数字。

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

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

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

    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
    

    【讨论】:

    • @user2013613 我很乐意,但我不认为在这里使用其他语言是个好主意。
    • @user2013613 是的,只要文件大小小于这个“内部缓冲区”,它就不会做任何事情。
    • @user2013613 没问题。您可以accept the answer 将问题标记为已解决。
    【解决方案2】:

    它列出了,给定的字符大小“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']

    【讨论】:

      【解决方案3】:

      根据文件的大小,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.
      

      所以,如果你的文件有 1000 行,你可以传入说... 65536,它一次只能读取那么多字节 + 足以完成下一行,返回所有行完全阅读。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 2017-03-31
        相关资源
        最近更新 更多