They are both pretty pythonic. To solve the second issue, in the second function the file will really be closed automatically. This is part of the protocol used with the operator with. Oddly enough, the file is not guaranteed to be closed in your first example (more on why in a second).
, with, - PEP 343:
with EXPR as VAR:
BLOCK
:
mgr = (EXPR)
exit = type(mgr).__exit__
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value
BLOCK
except:
exc = False
if not exit(mgr, *sys.exc_info()):
raise
finally:
if exc:
exit(mgr, None, None, None)
, - , . ; , , !