【问题标题】:Why does readline() not work after readlines()?为什么 readline() 在 readlines() 之后不起作用?
【发布时间】:2017-09-11 02:01:50
【问题描述】:

在 Python 中,假设我有:

f = open("file.txt", "r")
    a = f.readlines()
    b = f.readline()
    print a
    print b

print a 将显示文件的所有行,print b 将不显示任何内容。

反之亦然:

f = open("file.txt", "r")
    a = f.readline()
    b = f.readlines()
    print a
    print b

print a 显示第一行,但print b 将显示除第一行之外的所有行。

如果ab 都是readlines(),a 将显示所有行,b 将不显示任何内容。

为什么会这样?为什么两个命令不能彼此独立工作?有解决办法吗?

【问题讨论】:

  • Readlines 读取所有行,因此除非您返回文件开头,否则没有任何内容可读取。

标签: python file readline readlines


【解决方案1】:

因为首先执行.readlines() 将消耗所有读取缓冲区,不会留下任何东西供.readline() 获取。如果您想回到起点,请使用@abccd 在他的回答中已经提到的.seek(0)

>>> from StringIO import StringIO
>>> buffer = StringIO('''hi there
... next line
... another line
... 4th line''')
>>> buffer.readline()
'hi there\n'
>>> buffer.readlines()
['next line\n', 'another line\n', '4th line']
>>> buffer.seek(0)
>>> buffer.readlines()
['hi there\n', 'next line\n', 'another line\n', '4th line']

【讨论】:

    【解决方案2】:

    因为readlines读取了文件中的所有行,所以没有更多的行可以读取,再次读取文件,您可以使用f.seek(0)回到开头并从那里读取。

    【讨论】:

      【解决方案3】:

      文件有一个字节偏移量,每当您读取或写入它们时都会更新。这将达到您最初的预期:

      with open("file.txt") as f:
          a = f.readlines()
          f.seek(0)  # seek to the beginning of the file
          b = f.readline()
      

      现在a 是所有行,b 只是第一行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 1970-01-01
        • 2012-10-29
        • 2013-11-13
        • 1970-01-01
        相关资源
        最近更新 更多