为什么 readline() 在 readlines() 之后不起作用



在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()将消耗所有读取缓冲区,不会留下任何可供.readline()获取的内容。如果你想回到起点,请使用.seek(0),因为他的回答中已经提到了@abccd。

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

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

文件有一个字节偏移量,只要您读取或写入它们,它就会更新。这将完成您最初期望的操作:

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

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

相关内容

最新更新