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

2024-05-16 20:44:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,假设我有:

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

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

同样,反之亦然:

^{pr2}$

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

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

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


Tags: 命令txt内容readlineopenfileprint显示文件
2条回答

因为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只是第一行。在

{{cd2>第一次读取时,{cd2>将不消耗任何内容。如果你想回到开头,用.seek(0)作为@abccd在他的回答中已经提到。在

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

相关问题 更多 >