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 it's fine that sys.stdout
is closed after with
body, you can also use patterns like this:
# Use stdout when target is "-"
with open(target, "w") if target != "-" else sys.stdout as f:
f.write("hello world")
# Use stdout when target is falsy (None, empty string, ...)
with open(target, "w") if target else sys.stdout as f:
f.write("hello world")
or even more generally:
with target if isinstance(target, io.IOBase) else open(target, "w") as f:
f.write("hello world")