开发者

'With' in pre python 2.5

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 e开发者_JS百科fficiency is not important here.


Use try: except: finally:

The finally: clause can handle the close.

See http://www.python.org/dev/peps/pep-0343/ for alternatives.


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜