@contextlib.contextmanager<EOL>def smart_open_write(path=None, mode='<STR_LIT:wb>', encoding=None):
if path is not None:<EOL><INDENT>fh = io.open(path, mode=mode, encoding=encoding)<EOL><DEDENT>else:<EOL><INDENT>fh = io.open(sys.stdout.fileno(), mode=mode, encoding=encoding)<EOL><DEDENT>try:<EOL><INDENT>yield fh<EOL><DEDENT>finally:<EOL><INDENT>if fh.fileno() != sys.stdout.fileno():<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT>
Open a file for writing or return ``stdout``.

    Adapted from StackOverflow user "Wolph"
    (http://stackoverflow.com/a/17603000).