开发者

'With' in pre python 2.5

开发者 https://www.devze.com 2023-03-20 02:03 出处:网络
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. withare there to be more efficient t

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

精彩评论

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