0

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?

def
  • 7
  • 2

1 Answers1

0

The with open(filepath, mode) as a_file statement keeps the file open only inside of that segment - when it "exits" the segment there is no need for a_file.close(), regardless of where an exception is thrown - in open() or in yaml.load(...).

StrangeSorcerer
  • 304
  • 5
  • 11