博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python打开文本文档_带声明的Python –带打开的文件
阅读量:2531 次
发布时间:2019-05-11

本文共 5591 字,大约阅读时间需要 18 分钟。

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 .

Python with语句使我们在与上下文管理器一起工作时可以编写更简单的代码。 with语句是在下的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 , 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 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块引发错误,文件也可以关闭。

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 MyContextentering context of MyContextmy_context codeexit 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 Falsewith MyContext() as my_context:    print("my_context code")    raise TypeError("TypeError inside with block")

Output:

输出:

init method of MyContextentering context of MyContextmy_context codeexit context of MyContext - 
:: TypeError inside with block ::
Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/with_statement.py", line 32, in
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 Truewith MyContext() as my_context:    print("my_context code")    raise TypeError("TypeError inside with block")print("Done")

Output:

输出:

init method of MyContextentering context of MyContextmy_context codeexit context of MyContext - 
:: TypeError inside with block ::
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)

翻译自:

python打开文本文档

转载地址:http://fjlzd.baihongyu.com/

你可能感兴趣的文章
php opcode缓存
查看>>
springcloud之Feign、ribbon设置超时时间和重试机制的总结
查看>>
Go 结构体
查看>>
LINQ巩固
查看>>
观看杨老师(杨旭)Asp.Net Core MVC入门教程记录
查看>>
UIDynamic(物理仿真)
查看>>
Windows下安装Redis
查看>>
迷宫实现
查看>>
【字符编码】Java字符编码详细解答及问题探讨
查看>>
学习操作系统导图
查看>>
在线的JSON formate工具
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
xml解析
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
hdu--1698 Just a Hook(线段树+区间更新+懒惰标记)
查看>>
Python学习笔记-EXCEL操作
查看>>
二月二——头牙诗词
查看>>
《吴忠与富平》之四:汉三水属国(北地属国、安定属国)
查看>>
丁酉立秋喜逢风雨
查看>>