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
If you really must insist on something more "elegant", i.e. a one-liner:
>>> import sys
>>> target = "foo.txt"
>>> content = "foo"
>>> (lambda target, content: (lambda target, content: filter(lambda h: not h.write(content), (target,))[0].close())(open(target, 'w'), content) if target else sys.stdout.write(content))(target, content)
foo.txt appears and contains the text foo.