How to handle both `with open(…)` and `sys.stdout` nicely?

后端 未结 13 743
长发绾君心
长发绾君心 2020-12-07 14:47

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         


        
13条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 14:57

    if (out != sys.stdout):
        with open(out, 'wb') as f:
            f.write(data)
    else:
        out.write(data)
    

    Slight improvement in some cases.

提交回复
热议问题