def do_to_stdout():
    return do_stuff(sys.stdout)

def do_to_file(filename):
    with open(filename) as f:
        return do_stuff(f)
print(do_to_file(filename) if filename else do_to_stdout())
используя оператор Python 'with' с sys.stdout