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

后端 未结 13 742
长发绾君心
长发绾君心 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 15:02

    import contextlib
    import sys
    
    with contextlib.ExitStack() as stack:
        h = stack.enter_context(open(target, 'w')) if target else sys.stdout
        h.write(content)
    

    Just two extra lines if you're using Python 3.3 or higher: one line for the extra import and one line for the stack.enter_context.

提交回复
热议问题