59、有用过with statement吗?它的好处是什么?

python中的with语句是用来干嘛的?有什么作用?

with语句的作用是通过某种方式简化异常处理,它是所谓的上下文管理器的一种

用法举例如下:

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

当你要成对执行两个相关的操作的时候,这样就很方便,以上便是经典例子,with语句会在嵌套的代码执行之后,自动关闭文件。这种做法的还有另一个优势就是,无论嵌套的代码是以何种方式结束的,它都关闭文件。如果在嵌套的代码中发生异常,它能够在外部exception handler catch异常前关闭文件。如果嵌套代码有return/continue/break语句,它同样能够关闭文件。

我们也能够自己构造自己的上下文管理器

我们可以用contextlib中的context manager修饰器来实现,比如可以通过以下代码暂时改变当前目录然后执行一定操作后返回。

from contextlib import contextmanager
import os

@contextmanager
def working_directory(path):
    current_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(current_dir)

with working_directory("data/stuff"):
    # do something within data/stuff
# here I am back again in the original working directory
原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/9248581.html