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 (out != sys.stdout): with open(out, 'wb') as f: f.write(data) else: out.write(data)
Slight improvement in some cases.