在 python (2.7) 中,当使用 'with open' 时,我是否需要一个 'finally close' 块以防抛出错误(参见示例)
In python (2.7) when using 'with open', do I need a 'finally close' block in case of error thrown (see example)
使用'with open'时,如果发生异常,我是否需要finally 块来确保文件已关闭。 例如
try:
with open(self.some_path, "r") as a_file:
self.yaml_contents = yaml.load(a_file.read())
except IOError as ex:
logger.error("Failed to open (or load) settings file '{}' because '{}'".format(self.some_path,ex.strerror))
raise
如果 open() 抛出异常,假设它确实打开了文件,它会被关闭还是我需要关闭它? 另外,如果 yaml.load() 抛出,那么 with open 是否仍会完成,即 close() 文件?
try:
with open(self.some_path, "r") as a_file:
self.yaml_contents = yaml.load(a_file.read())
except IOError as ex:
logger.error("Failed to open (or load) settings file {} because {}".format(self.some_path,ex.strerror))
raise
finally:
a_file.close()
但是现在 a_file 不在范围内,对吗?
with open(filepath, mode) as a_file
语句使文件仅在该段内打开 - 当它“退出”该段时,不需要 a_file.close()
,无论在何处抛出异常 - 在 open()
或 yaml.load(...)
.