它们都非常pythonic.要解决第二个问题,在第二个函数中,文件确实会自动关闭.这是与with语句一起使用的协议的一部分.具有讽刺意味的是,不保证在第一个示例中关闭该文件(更多关于为什么在一秒钟内).
最终,我会选择使用with语句,这就是为什么 – 根据PEP 343:
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)
正如您所看到的,在这种情况下您可以获得很多保护 – 无论在干预代码中发生什么,您的文件都可以保证关闭.这也有助于提高可读性;想象一下,如果每次打开文件时都必须放置这么大的代码块!