Skip to content Skip to sidebar Skip to footer

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

 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

Solution 2:

USE THIS

for i, line in enumerate(f):
    if i == 0 :
         print line
    else:
         print 'NewLine: %s' % line

Post a Comment for "Python:Why Readline() Function Doesn't Work For File Looping"