[Tutor] iterating over a urllib.urlopen().read() object

Alan Gauld alan.gauld at blueyonder.co.uk
Mon Dec 8 04:31:49 EST 2003


>  f = urllib.urlopen(source_url)
>  BUFSIZE = 8192
>
>  while True:
>      data = f.read(BUFSIZE)
>      if not data: break
>      p.feed(data)
>
> I didn't like the "while True:" construct, and too smart for my
own good,
> tried this instead:
>
>  for data in f.read(BUFSIZE):
>       p.feed(data)

The while loop keeps reading until nothing comes back.
The for vesion reads once then loops for each item in
the chunk read. They are quite different concepts.

"While" is the correct loop in this case because we don't
know in advance how many iterations we need to go through.
Although personally I'd prefer

data = f.read(BUFSIZE)
while data:
   p.feed(data)
   data = f.read(BUFSIZE)

But that's just me...

Alan G.




More information about the Tutor mailing list