When using 'with open' if an exception occurs do I need a finally block to ensure the file is closed. e.g.
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
If open() throws, assuming it did actually open the file, will it be closed or do I need to close it? Also if yaml.load() throws, then will the with open still complete i.e. close() the file?
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()
But now a_file is not in scope, right?