Building loop with some exceptions?
Matimus
mccredie at gmail.com
Tue Nov 4 15:10:28 EST 2008
On Nov 4, 11:20 am, Gilles Ganault <nos... at nospam.com> wrote:
> Hello
>
> I need to call a URL through a loop that starts at 01 and ends at 99,
> but some of the steps must be ignored:
>
> =====
> url = "http://www.acme.com/list?code="
> p = re.compile("^(\d+)\t(.+)$")
>
> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
> f = urllib.urlopen(url + i)
> page = f.read()
> f.close()
>
> for line in page:
> m = p.search(line)
> if m:
> code = m.group(1)
> label = m.group(2)
>
> print "Code=" + code + " # Label=" + label
> =====
>
> I'm clueless at what the Python way is to do this :-/
>
> Thank you for any help.
I would just do something like this (not tested):
url_tmpl = "http://www.acme.com/list?code=%02d"
p = re.compile("^(\d+)\t(.+)$")
EXCLUDED_VALUES = 4, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89
for i in xrange(1,100):
if i in EXCLUDED_VALUES:
continue
f = urllib.urlopen(url_tmpl % i)
try:
for line in f:
m = p.search(line)
if m:
code = m.group(1)
label = m.group(2)
print "Code=", code, "# Label=", label
finally:
f.close()
More information about the Python-list
mailing list