Reputation: 1
Is there a means of converting a python 'with' statement into a format that can be used in previous versions of python. 4 month's work hinging on this question. with are there to be more efficient than their previous counterparts, but efficiency is not important here.
Upvotes: 0
Views: 97
Reputation: 149
As S.Lott has stated, try and finally should handle the work of the with clause. I'm not sure that with
actually catches any errors, so given that assumption:
with open(file_name,mode) as name: # Or whatever expression
do_this()
can be replaced with
try:
name = open(filename,mode) # Or whatever expression
do_this()
finally:
name.close()
Upvotes: 0
Reputation: 391952
Use try:
except:
finally:
The finally:
clause can handle the close.
See http://www.python.org/dev/peps/pep-0343/ for alternatives.
Upvotes: 3