在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
将显示除第一行之外的所有行。
如果 a
和 b
都是 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
只是第一行。