urllib2 - iteration over non-sequence
Erik Max Francis
max at alcyone.com
Sat Jun 9 21:57:06 EDT 2007
Gary Herron wrote:
> So... You must explicitly read the contents of the file-like object
> yourself, and loop through the lines you self. However, fear not --
> it's easy. The socket._fileobject object provides a method "readlines"
> that reads the *entire* contents of the object, and returns a list of
> lines. And you can iterate through that list of lines. Like this:
>
> import urllib2
> url = urllib2.urlopen('http://www.google.com')
> for line in url.readlines():
> print line
> url.close()
This is really wasteful, as there's no point in reading in the whole
file before iterating over it. To get the same effect as file iteration
in later versions, use the .xreadlines method::
for line in aFile.xreadlines():
...
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
If you flee from terror, then terror continues to chase you.
-- Benjamin Netanyahu
More information about the Python-list
mailing list