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

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

    If it's fine that sys.stdout is closed after with body, you can also use patterns like this:

    # Use stdout when target is "-"
    with open(target, "w") if target != "-" else sys.stdout as f:
        f.write("hello world")
    
    # Use stdout when target is falsy (None, empty string, ...)
    with open(target, "w") if target else sys.stdout as f:
        f.write("hello world")
    

    or even more generally:

    with target if isinstance(target, io.IOBase) else open(target, "w") as f:
        f.write("hello world")
    
    0 讨论(0)
提交回复
热议问题