Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:
if target:
with open(target, \'w\') as h
The following solution is not a beauty, but from a time long, long ago; just before with ...
handler = open(path, mode = 'a') if path else sys.stdout
try:
print('stuff', file = handler)
... # other stuff or more writes/prints, etc.
except Exception as e:
if not (path is None): handler.close()
raise e
handler.close()