I noticed some strange behavior today playing around with next()
and readline()
. It seems that both functions produce the same results (which is what I expect). However, when I mix them, I get a ValueError
. Here's what I did:
>>> f = open("text.txt", 'r')
>>> f.readline()
'line 0
'
>>> f.readline()
'line 1
'
>>> f.readline()
'line 2
'
>>> f.next()
'line 3
'
>>> f.next()
'line 4
'
>>> f.readline()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Mixing iteration and read methods would lose data
>>>
>>> f = open("text.txt", 'r')
>>> f.next()
'line 0
'
>>> f.next()
'line 1
'
>>> f.next()
'line 2
'
>>> f.readline()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Mixing iteration and read methods would lose data
So the overall question here is what's going on underneath the hood that causes this error?
Some questions that might get answered along with but I would like to hear an answer for if not:
- What are the differences between
next()
and readline()
?
- When I do
for f in file:
which function am I calling (and does it matter)?
- Why can I call
next()
after readline()
, but not the other way around?
Thanks in advance,
I don't think it matters, but in case this is version dependent, I'm on Python 2.7.6 for Windows
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…