I have the following code:
#!/usr/bin/pythonf = 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 lineNext 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
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 syswith open(sys.argv[1]) as inf:fit = iter(inf)for line in fit:print "current", linetry:print "next", fit.next()except StopIteration:pass