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 operationstxt_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 operationsprint("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 Falsewith 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 Truewith 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)

  • Context Manager上下文管理器
  • Python.org DocsPython.org文件

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

python打开文本文档

python打开文本文档_带声明的Python –带打开的文件相关推荐

  1. cmd命令打开文本文档_震惊!我竟然通过控制台打开了QQ!

    震惊且免,本文按逆序讲解实现的原理和如何实现. 如何实现 1.设置系统的环境变量.将桌面加入环境变量.即将下列两者加入环境变量: 个人桌面: C:Users你的用户名Desktop: 公共桌面: C: ...

  2. python打开文本文档时不允许其他程序修改_2.2.4 python 文件处理 - 文件其他操作修改...

    文件操作的其它功能 def fileno(self, *args, **kwargs): # real signature unknown # 返回文件句柄在内核中的索引值,以后做IO多路复用时可以用 ...

  3. python生成接口文档_使用apiDoc实现python接口文档编写

    使用apiDoc实现python接口文档编写 apiDoc的安装 npm install apidoc -g 生成api的终端命令:apidoc -i 代码所在路径-o 生成文件的路径 接口文档的编写 ...

  4. cmd命令打开文本文档_善用bat命令提高办公效率

    bat指的是批量处理文件命令,在 Windows 系统使用.而 bat 文件是可执行文件,由命令构成,其中可以包含对其它程序调用,文件后缀是 bat 或 cmd.在文件中,一行内容就是一条执行命令,可 ...

  5. cmd命令打开文本文档_win10自带照片应用打开太慢,改用win7照片查看器

    win10照片这个应用的功能确实多了很多,但平时我们只是看个图片,它却打开太慢,不如win7照片查看器来的爽.但是win7照片查看器在win10里是隐藏的,需要给它在注册表里手动添加支持的格式,就是让 ...

  6. python excel 打印文档_教你如何用Python轻轻松松操作Excel、Word、CSV,一文就够了,赶紧码住!!!...

    原标题:教你如何用Python轻轻松松操作Excel.Word.CSV,一文就够了,赶紧码住!!! 作者:奈何缘浅wyj Python 操作 Excel 常用工具 数据处理是 Python 的一大应用 ...

  7. python 批量打印文档_使用python将Excel数据填充Word模板并生成Word

    [项目需求] Excel中有一万多条学生学平险数据,需要给每位学生打印购买回执单,回执单包括学生姓名,身份证号,学校等信息,目前只能从Excel拷贝数据到Word模板中,然后打印,效率及其低下,寻求帮 ...

  8. 脚本文档_创建完美的架构文档脚本

    脚本文档 描述 (Description) System views allow us to gain access to information about any objects within S ...

  9. cmd命令打开文本文档_Windows10家庭版打开「本地组策略」

    在win10家庭版系统中默认是没有组策略的,组策略打不开无法进行相关所需要的一些设置,该如何解决呢?可以通过将[Windows10 家庭版]升级到[Windows10专业版]来解决,但这是不推荐的.那 ...

最新文章

  1. verilog中如何拆分一个数
  2. ajax php 区别,PHP中AJAX比较(转)
  3. pytorch nn.Conv2d
  4. fedora linux操作系统安装,Fedora-10 Linux操作系统的安装,Fedora Linux的安装锦集收藏,图文并茂详解...
  5. 4.聚合aggregate
  6. 赫夫曼树编码的算法及应用习题--数据结构
  7. C++重载下标运算符
  8. Spring Boot笔记-解决前后端分离在开发时的跨域问题
  9. 有一门课不及格的学生(信息学奥赛一本通-T1048)
  10. Apowersoft ApowerMirror v1.4.5 终身商业授权破解版 安卓/iPhone投屏控制软件
  11. java基于springboot高校信息资源共享网站系统
  12. 我用Python爬取了李沧最近一年多的二手房成交数据得出以下结论
  13. 【Wordpress主题】Sakuraio主题的使用与优化
  14. 在sagemath中安装第三方库
  15. java autoconf_「Autoconf」- 安装 @20210202
  16. FatTree胖树拓扑结构
  17. 安装KALI里面的翻译工具
  18. Python高级培训第一次作业(寒假)
  19. Active Form显示标题栏及页面跳转
  20. sms deliver解码

热门文章

  1. [转载] Python基础——Numpy库超详细介绍+实例分析+附代码
  2. [转载] Java中为什么要有重载现象
  3. verilog之状态机的结构
  4. Mybatis案例超详解
  5. mysql连接数过多
  6. c语言里面你不知道的break与switch,contiune的用法
  7. 【转】Numpy三维数组的转置与交换轴
  8. 第十六篇 Python之迭代器与生成器
  9. 使用mysql innodb 使用5.7的json类型遇到的坑和解决办法
  10. django 数据库交互2