from contextlib import contextmanager

@contextmanager
def tempOpen(path, mode):
    file = open(path, mode)
try:
    yield file
finally:
    file.close()
Python using 'with' to delete a file after use