-1

So I was reading up on how to properly use the with keyword in python, and I could not figure out the best way to handle an exception that might occur within a with statement. So I am writing a very simple script to write a value to a file.

json = loads(response.read())
try:
  with open(args.file, 'w') as t:
    try:
      t.write(json[TOKEN])
      print "Wrote token to {file!s}".format(file=args.file)
    except KeyError:
      print "Unable to find {token!s} in response".format(token=TOKEN)
except IOError as bad:
  print "Ran into an error while trying to open file {file!s}".format(file=args.file)
  print "{err!s}".format(bad.message)

I want to be certain that if the KeyError is caught that the file will still close properly.

cs95
  • 274,032
  • 76
  • 480
  • 537
dblanken
  • 56
  • 2
  • 5
  • 1
    Possible duplicate of [What is the python "with" statement designed for?](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for) – bgse Nov 14 '17 at 18:24
  • "I want to be certain that if the KeyError is caught that the file will still close properly." - do you think it *won't* be closed with your current code? – user2357112 supports Monica Nov 14 '17 at 18:25

1 Answers1

0

I found the answer in the following document https://www.python.org/dev/peps/pep-0343/ that was in a link that was provided in the comments.

According to the link here is what happens when you use the with keyword. In order to use the with keyword your expression must have an __enter__(self) and an __exit__(self, type, value, traceback) method. Python will attempt to call the__enter__() method, followed by your block of code, and then run a finally with the __exit(self, type, value, traceback) method. This will insure that that set up and tear down all get accomplished accordingly. At least that is my understanding of the keyword.

dblanken
  • 56
  • 2
  • 5