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

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

    If you really must insist on something more "elegant", i.e. a one-liner:

    >>> import sys
    >>> target = "foo.txt"
    >>> content = "foo"
    >>> (lambda target, content: (lambda target, content: filter(lambda h: not h.write(content), (target,))[0].close())(open(target, 'w'), content) if target else sys.stdout.write(content))(target, content)
    

    foo.txt appears and contains the text foo.

提交回复
热议问题