Python:why Readline() Function Doesn't Work For File Looping
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:
Solution 1:
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
withopen(sys.argv[1]) as inf:
fit = iter(inf)
for line in fit:
print"current", line
try:
print"next", fit.next()
except StopIteration:
pass
Post a Comment for "Python:why Readline() Function Doesn't Work For File Looping"