Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code:

#!/usr/bin/python

f = open('file','r')

for line in f:
    print line 
    print 'Next line ', f.readline()
f.close()

This gives the following output:

This is the first line

Next line
That was the first line
Next line

Why doesn't the readline() function works inside the loop? Shouldn't it print the next line of the file?
I am using the following file as input

This is the first line
That was the first line
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are messing up the internal state of the file-iteration, because for optimization-reasons, iterating over a file will read it chunk-wise, and perform the split on that. The explicit readline()-call will be confused by this (or confuse the iteration).

To achieve what you want, make the iterator explicit:

 import sys

 with open(sys.argv[1]) as inf:
     fit = iter(inf)
     for line in fit:
         print "current", line
         try:
             print "next", fit.next()
         except StopIteration:
             pass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...