closing files properly opened with urllib2.urlopen()
Question: I have following code in a python script

    
    
      try:
        # send the query request
        sf = urllib2.urlopen(search_query)
        search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
        sf.close()
      except Exception, err:
        print("Couldn't get programme information.")
        print(str(err))
        return
    

I'm concerned because if I encounter an error on `sf.read()`, then
`sf.clsoe()` is not called. I tried putting `sf.close()` in a `finally` block,
but if there's an exception on `urlopen()` then there's no file to close and I
encounter an exception in the `finally` block!

So then I tried

    
    
      try:
        with urllib2.urlopen(search_query) as sf:
          search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
      except Exception, err:
        print("Couldn't get programme information.")
        print(str(err))
        return
    

but this raised a invalid syntax error on the `with...` line. How can I best
handle this, I feel stupid!

As commenters have pointed out, I am using Pys60 which is python 2.5.4


Answer: I would use contextlib.closing (in combination with from __future__ import
with_statement for old Python versions):

    
    
    from contextlib import closing
    
    with closing(urllib2.urlopen('http://blah')) as sf:
        search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
    

Or, if you want to avoid the with statement:

    
    
    try:
        sf = None
        sf = urllib2.urlopen('http://blah')
        search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
    finally:
        if sf:
            sf.close()
    

Not quite as elegant though.

