[Tutor] Readlines
Don Arnold
Don Arnold" <darnold02@sprynet.com
Sun Jun 22 00:11:01 2003
----- Original Message -----
From: "Adam Vardy" <anvardy@roadrunner.nf.net>
To: <tutor@python.org>
Sent: Saturday, June 21, 2003 2:49 PM
Subject: Re: [Tutor] Readlines
>
> Now I'm trying Read(). I have a couple observations, and wonder what
> you folks think. Take the code below. I notice that Read() is
> apparently incredibly slow! Text appears on screen, cursor slowly
> gliding across. Which surprises as it is only reading a byte at a
> time. On a Gigahertz machine.
>
> The other thing is I notice this extract does not run corrently. It's
> just supposed to print what it reads. And a part to pause for a
> moment, after its printed many lines. (Thought that would be
> necessary!)
>
> You'll probably notice the error quicker than I have. I was just
> wondering, how can you prevent errors. Suppose its just too warm in
> the summer to pick out things easily. Well, would other ways to
> structure your code occur to you that may minimize the liklihood of
> such errors?
>
> #
> fhand=open(filepath,'r')
>
> while c!='':
> while z!='\n':
> z=fhand.read(1)
> print z,
> ln=ln+1
> c=z
> if ln%100==0:
> print ln
> time.sleep(1)
>
> print "DONE."
>
Well, since filepath, c, z, and ln aren't defined (and time wasn't
imported), this script doesn't run. If you do define them and add the
import, you still have problems: as soon as you hit your first '\n', you
stop reading from the file and just keep looping, pausing 1 second every 100
iterations. File processing like this is usually done by performing a
priming read to set up your looping condition, then having another read at
the end of your loop body:
import time
filepath = 'c:/temp2/infile.txt'
fhand=open(filepath,'r')
ln = 0
z = fhand.read(1)
while z != '':
if z == '\n':
ln = ln + 1
if ln % 2 == 0:
print '[%s]' % ln
time.sleep(1)
else:
print
else:
print z,
z=fhand.read(1)
fhand.close()
print "DONE."
>>>
l i n e 1
l i n e 2 [2]
l i n e 3
l i n e 4 [4]
l i n e 5
l i n e 6 [6]
l i n e 7
l i n e 8 [8]
l i n e 9
l i n e 1 0 [10]
l i n e 1 1
l i n e 1 2 [12]
l i n e 1 3
l i n e 1 4 [14]
l i n e 1 5
l i n e 1 6 [16]
l i n e 1 7
l i n e 1 8 [18]
l i n e 1 9
l i n e 2 0 [20]
DONE.
>>>
I'm still not sure why you're not just using readline( ), though:
import time
filepath = 'c:/temp2/infile.txt'
fhand=open(filepath,'r')
z = fhand.readline()
ln = 0
while z != '':
print z[:-1], ## don't print trailing newline since we might want
to print the line #
ln = ln + 1
if ln % 2 == 0:
print ' [%s]' % ln
time.sleep(1)
else:
print
z=fhand.readline()
fhand.close()
print "DONE."
HTH,
Don