打破还是退出“ with”陈述?

发布于 2021-01-29 18:30:45

我只想with在某些情况下退出声明:

with open(path) as f:
    print 'before condition'
    if <condition>: break #syntax error!
    print 'after condition'

当然,以上方法不起作用。有没有办法做到这一点?(我知道我可以反转条件:if not <condition>: print 'after condition'-像上面一样吗?)

关注者
0
被浏览
42
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    最好的方法是将其封装在一个函数中并使用return

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看