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

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

    Stick with your current code. It's simple and you can tell exactly what it's doing just by glancing at it.

    Another way would be with an inline if:

    handle = open(target, 'w') if target else sys.stdout
    handle.write(content)
    
    if handle is not sys.stdout:
        handle.close()
    

    But that isn't much shorter than what you have and it looks arguably worse.

    You could also make sys.stdout unclosable, but that doesn't seem too Pythonic:

    sys.stdout.close = lambda: None
    
    with (open(target, 'w') if target else sys.stdout) as handle:
        handle.write(content)
    

提交回复
热议问题