这是代码
with open(myfile) as f: data = f.read() process(data)
相当于这个
try: f = open(myfile) data = f.read() process(f) finally: f.close()
还是以下一个?
f = open(myfile) try: data = f.read() process(f) finally: f.close()
本文:http://effbot.org/zone/python-with-statement.htm建议(如果我理解正确的话)后者是真的.但是,前者对我来说更有意义.如果我错了,我错过了什么?
根据文件:
提出了一个新语句,其语法如下:
with EXPR as VAR: BLOCK上述声明的译文如下:
mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present BLOCK except: # The exceptional case is handled here exc = False if not exit(mgr, *sys.exc_info()): raise # The exception is swallowed if exit() returns true finally: # The normal and non-local-goto cases are handled here if exc: exit(mgr, None, None, None)
这是您的第二个代码段的扩展版本.初始化在try ... finaly
阻止之前进行.