如果发生异常,使用'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
语句只在该段内部保持文件打开,当它"退出";无论在open()
或yaml.load(...)
中的哪里抛出异常,都不需要a_file.close()
。