Break or exit out of “with” statement?

后端 未结 12 2243
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 11:04

I\'d just like to exit out of a with statement under certain conditions:

with open(path) as f:
    print \'before condition\'
    if 

        
12条回答
  •  一个人的身影
    2020-12-02 11:33

    The best way would be to encapsulate it in a function and use return:

    def do_it():
        with open(path) as f:
            print 'before condition'
            if :
                return
            print 'after condition'
    

提交回复
热议问题