简体   繁体   中英

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:

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

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

USE THIS

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM