readline skips on line

.:|:. ng at hardlight.couk.com
Tue Apr 11 13:40:39 CEST 2000


> try this:
>
> f=open('test.txt', 'r')
>
> while 1:
>   line=f.readline()
>   if not line:
>     break
>   print line
>
> print "ready"

while this is functionallty correct I prefer :

f=open('text.txt', 'r')
line = f.readline()
while line:
    print line
    line = f.readline()

print 'ready'


which is actually a few cycles quicker however
1. the print will append and extra carriage return on the end putting blank
lines in
2. the data will be lost to the porogram
3. repeated disk reads though buffered will slow your inner loop
4. it looks ugly

i'd go for this :

f = open('text.txt', 'r')
lines = f.readlines()

for line in lines:
    print line[:-1]

print 'ready'


> > f=open('test.txt', 'r')
> > while f.readline()!='':
> >     print f.readline()
> > print 'ready'
> >
> > but when it is runned, it wil print out the lines in the text file, but
it
> > skips all the the odd line, it only displays line 2,4,6,8,10 and further






More information about the Python-list mailing list