python打开文本文档_带声明的Python –带打开的文件

python打开文本文档

Python with statement allows us to write simpler code when working with context managers. The with statement was introduced in Python 2.5 under PEP 343.

Python with语句使我们在与上下文管理器一起工作时可以编写更简单的代码。 with语句是在PEP 343下的Python 2.5中引入的。

1.什么是上下文管理器? (1. What is a Context Manager?)

A context manager is an object that creates and manages a runtime context. The typical usage of context managers is to save and restore the global state, lock and unlock resources, opening and closing files, etc.

上下文管理器是创建和管理运行时上下文的对象。 上下文管理器的典型用法是保存和还原全局状态,锁定和解锁资源,打开和关闭文件等。

2.上下文管理器的生命周期 (2. The lifecycle of Context Manager)

The context manager object must define the enter() and exit() methods. These methods are called when the runtime context is created and when it’s destroyed.

上下文管理器对象必须定义enter()exit()方法。 创建运行时上下文以及销毁它们时将调用这些方法。

3.为什么我们需要Python with语句? (3. Why do we need Python with statement?)

When we have to work with a file, we have to first open it. It creates a runtime context manager for the file. After the work is done, we have to manually close the file so that the context manager terminates properly.

当我们必须使用文件时,我们必须首先打开它。 它为文件创建一个运行时上下文管理器。 工作完成后,我们必须手动关闭文件,以便上下文管理器正确终止。

We generally use the try-except block to work with the file and finally block to close the file. This makes sure that the file gets closed even if there is an error raised by the try block.

我们通常使用try-except块来处理文件,最后使用块来关闭文件。 这样可以确保即使try块引发错误,文件也可以关闭。

try:
    txt_file = open("abc.txt")
    # do some operations
    txt_file.close()
except FileNotFoundError as e:
    print(e)
finally:
    txt_file.close()

Python with statement takes care of calling the exit() method of the context manager when the code inside the with block is executed.

执行with块中的代码时,Python with语句负责调用上下文管理器的exit()方法。

Let’s rewrite the above code using the with statement.

让我们使用with语句重写上面的代码。

with open("abc.txt") as file:
    # do some operations
    print("Done")

The code is much simpler to read and we don’t have to worry about closing the file every time.

该代码更易于阅读,我们不必担心每次都关闭文件。

4. Python与语句自定义上下文管理器示例 (4. Python with Statement Custom Context Manager Example)

We can define our own custom context manager by implementing enter() and exit() methods.

我们可以通过实现enter()和exit()方法来定义自己的自定义上下文管理器。

class MyContext:

    def __init__(self):
        print("init method of MyContext")

    def __enter__(self):
        print("entering context of MyContext")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit context of MyContext")


with MyContext() as my_context:
    print("my_context code")

Output:

输出:

init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext
  • The context manager is initialized.

    上下文管理器已初始化。
  • Then the __enter__() method is called for the context manager object.

    然后,为上下文管理器对象调用__enter __()方法。
  • The code inside the with block is executed.

    with块中的代码被执行。
  • Finally, the __exit__() method of the context manager is called.

    最后,调用上下文管理器的__exit __()方法。

5.带有打开文件的Python (5. Python with open files)

Python 3.1 enhanced the with statement to support multiple context managers. Let’s see how to open multiple files using the with statement.

Python 3.1增强了with语句,以支持多个上下文管理器。 让我们看看如何使用with语句打开多个文件。

with open("abc.txt") as file1, open("abc.txt") as file2:
    pass

The above code is equivalent to multiple nested with statements.

上面的代码等效于多个嵌套的with语句。

with open("abc.txt") as file1:
    with open("abc.txt") as file2:
        pass

6.带有语句异常情况的Python (6. Python with statement exception scenarios)

If there is an exception raised in the with block, its type, value, and traceback are passed as arguments to __exit__().

如果with块中引发了异常,则将其类型,值和回溯作为参数传递给__exit __()。

If the __exit__() method returns False, then the exception is re-raised.

如果__exit __()方法返回False,则重新引发异常。

class MyContext:

    def __init__(self):
        print("init method of MyContext")

    def __enter__(self):
        print("entering context of MyContext")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'exit context of MyContext - {exc_type} :: {exc_val} :: {exc_tb}')
        return False


with MyContext() as my_context:
    print("my_context code")
    raise TypeError("TypeError inside with block")

Output:

输出:

init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext - <class 'TypeError'> :: TypeError inside with block :: <traceback object at 0x1044e8f48>
Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/with_statement.py", line 32, in <module>
    raise TypeError("TypeError inside with block")
TypeError: TypeError inside with block

If the __exit__() method returns True, then the exception is consumed and normal execution continues.

如果__exit __()方法返回True,则使用该异常并继续正常执行。

class MyContext:

    def __init__(self):
        print("init method of MyContext")

    def __enter__(self):
        print("entering context of MyContext")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'exit context of MyContext - {exc_type} :: {exc_val} :: {exc_tb}')
        return True


with MyContext() as my_context:
    print("my_context code")
    raise TypeError("TypeError inside with block")

print("Done")

Output:

输出:

init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext - <class 'TypeError'> :: TypeError inside with block :: <traceback object at 0x102149e08>
Done

7.结论 (7. Conclusion)

Python with statement takes care of managing the life cycle of the context manager. The code looks small and removes the chance of leaving the context manager open due to poor programming.

Python with语句负责管理上下文管理器的生命周期。 该代码看起来很小,并且消除了由于不良编程而使上下文管理器保持打开状态的机会。

8.参考 (8. References)

翻译自: https://www.journaldev.com/33273/python-with-statement-with-open-file

python打开文本文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值