while loop with f.readline()

D-Man dsh8290 at rit.edu
Tue Feb 13 12:39:08 EST 2001


On Tue, Feb 13, 2001 at 03:29:00PM -0300, Chris Richard Adams wrote:
| I'm trying to create a loop that reads through a simple file with
| strings on each line.
| 
| f=open('/tmp/xferlog', 'r')
| while f.readline():

This reads line 1 , 3, 5

|  line = f.readline()

this reads lines 2 , 4 

|  print line

this prints the lines stored in 'line', lines 2, 4

| 
| Problem 1: Although I know there are five lines in the file - it only
| prints the 3rd and 4th line.  Is my usage above correct for this - I'd
| expect to see all lines.
| 
| Problem 2: How do define the range of the while loop: for example if I
| place f.close() in the list of items wto go through in the loop:
| 
| 
| f=open('/tmp/xferlog', 'r')
| while f.readline():
|  line = f.readline()
|  print line
|  f.close()
| 
| How do i code the loop to know that it should be executed after the
| loop...not after each iteration???
| 
| Thanks!
| 

f = open( '/tmp/xferlog' , 'r' )
for line in f.readlines() :
    print line
f.close() # not indented, this happens after the loop

If you are using Python 2.1 or greater you can use the f.xreadlines()
function which won't read the entire file at once.

Alternatively :

f = open( '/tmp/xferlog' , 'r' )
while 1 :
    line = f.readline()
    if not line : break # stop the loop if no line was read
    print line
f.close() # after the loop, not in it


or

f = open( '/tmp/xferlog' , 'r' )
line = f.readline()
while line :
    print line
    line = f.readline()
f.close()



I prefer the for loop the best, and will be great when 2.1 is released
(with the xreadlines function).

HTH,
-D





More information about the Python-list mailing list