python - closing files properly opened with urllib2.urlopen() -
i have following code in python script
try: # send query request sf = urllib2.urlopen(search_query) search_soup = beautifulsoup.beautifulstonesoup(sf.read()) sf.close() except exception, err: print("couldn't programme information.") print(str(err)) return i'm concerned because if encounter error on sf.read(), sf.clsoe() not called. tried putting sf.close() in finally block, if there's exception on urlopen() there's no file close , encounter exception in finally block!
so tried
try: urllib2.urlopen(search_query) sf: search_soup = beautifulsoup.beautifulstonesoup(sf.read()) except exception, err: print("couldn't programme information.") print(str(err)) return but raised invalid syntax error on with... line. how can best handle this, feel stupid!
as commenters have pointed out, using pys60 python 2.5.4
why not try closing sf, , passing if doesn't exist?
import urllib2 try: search_query = 'http://blah' sf = urllib2.urlopen(search_query) search_soup = beautifulsoup.beautifulstonesoup(sf.read()) except urllib2.urlerror, err: print(err.reason) finally: try: sf.close() except nameerror: pass
Comments
Post a Comment