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

后端 未结 5 1141
别跟我提以往
别跟我提以往 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:53

    This seems to solve all of your concerns.

    if file_name is not None:
        with open(file_name) as fh:
            do_something(fh)
    else:
            do_something(None)
    

提交回复
热议问题