Is it possible to have an optional with/as statement in python?

后端 未结 5 1148
别跟我提以往
别跟我提以往 2021-01-04 03:25

Instead of this:

FILE = open(f)
do_something(FILE)
FILE.close()

it\'s better to use this:

with open(f) as FILE:
    do_some         


        
5条回答
  •  滥情空心
    2021-01-04 03:48

    While all of the other answers are excellent, and preferable, note that the with expression may be any expression, so you can do:

    with (open(file) if file is not None else None) as FILE:
        pass
    

    Note that if the else clause were evaluated, to yield None this would result in an exception, because NoneType does not support the appropriate operations to be used as a context manager.

提交回复
热议问题