import contextlib
import sys
with contextlib.ExitStack() as stack:
h = stack.enter_context(open(target, 'w')) if target else sys.stdout
h.write(content)
Just two extra lines if you're using Python 3.3 or higher: one line for the extra import and one line for the stack.enter_context.