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

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

    I'd also go for a simple wrapper function, which can be pretty simple if you can ignore the mode (and consequently stdin vs. stdout), for example:

    from contextlib import contextmanager
    import sys
    
    @contextmanager
    def open_or_stdout(filename):
        if filename != '-':
            with open(filename, 'w') as f:
                yield f
        else:
            yield sys.stdout
    

提交回复
热议问题