def do_stuff(file):
    return file.readline()

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())
using Python 'with' statement with sys.stdout