2017-04-14 19 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只是第一線。

相關問題