Break or exit out of “with” statement?

后端 未结 12 2209
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  -上瘾入骨i
    2020-12-02 11:53

    f = open("somefile","r")
    for line in f.readlines():
           if somecondition: break;
    f.close()
    

    I dont think you can break out of the with... you need to use a loop...

    [edit] or just do the function method others mentioned

提交回复
热议问题