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.
 
    