美文网首页
Python with statement

Python with statement

作者: 怀瑾握瑜 | 来源:发表于2014-07-02 11:48 被阅读35次

    常用形式:

     with open('output.txt', 'w') as f:
         f.write('Hi there, !')
    

    内在机制:

    类似try...except...finally, 在with的block中try,不管是否出现异常,都会 finally关闭打开的文件,即使在循环中遭遇了continue或者break也照样以 finally形式执行关闭

    可以多重:

    with A() as a, B() as b:
         do something
    

    相关文章

      网友评论

          本文标题:Python with statement

          本文链接:https://www.haomeiwen.com/subject/oyujtttx.html