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

后端 未结 13 749
长发绾君心
长发绾君心 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:59

    The following solution is not a beauty, but from a time long, long ago; just before with ...

    handler = open(path, mode = 'a') if path else sys.stdout
    try:
        print('stuff', file = handler)
        ... # other stuff or more writes/prints, etc.
    except Exception as e:
        if not (path is None): handler.close()
        raise e
    handler.close()
    

提交回复
热议问题