2017-04-14 20 views
-1

在Python,说我有:为什么readline()在readlines()之后不起作用?

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将不显示任何内容。

为什么会发生这种情况?为什么两个命令都不能独立工作?有没有解决方法?

+2

readlines读取所有行,所以除非您回到文件的开头,否则没有什么可读的。 –

回答

3

,因为这样做.readlines()首先将消耗所有读缓冲区只留下了.readline()要从中提取的。如果您想回到起点,请使用.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'] 
2

因为readlines读取文件中的所有行,所以没有更多的行留下来读取,再次读取该文件,你可以使用f.seek(0)走回到起点,并从那里读取。

1

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

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

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

相关问题