博客
关于我
python中的with学习
阅读量:796 次
发布时间:2023-03-09

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

Python with 语句:简洁处理文件操作与异常

在编程实践中,文件操作是非常常见的任务。然而,文件操作往往伴随着一些需要注意的事后处理。Python 的 with 语句提供了一种简洁且安全的方式来处理文件操作和其他资源,避免了手动管理资源的复杂性。


1. 文件操作的常规方式

传统的文件读取操作通常如下:

1. f = open('../test.txt', 'r')2. data = f.read()3. f.close()

这种写法虽然简单,但存在一个潜在的问题:如果程序在读取文件期间中断或遇到错误,f.close() 可能不会被执行,导致文件资源泄漏或其他潜在风险。


2. 使用 with 语句的优势

with 语句引入了一个称为 上下文管理器 的概念。它能够自动管理文件或其他资源的打开和关闭,确保在异常发生时也能妥善处理资源。

修改后的代码如下:

1. with open('../test.txt', 'r') as f:2.     data = f.read()
  • 自动化处理:with 语句会在代码块执行完成后自动调用 close() 方法,确保文件被正确关闭。
  • 异常安全:即使在读取过程中发生异常,with 语句仍能确保资源被正确处理。

3. 上下文管理器的工作原理

with 语句背后的核心是上下文管理器类,其必须实现 __enter__() 和 __exit__() 方法。

  • __enter__():在进入上下文时调用,返回一个对象(通常是文件对象)。
  • __exit__():在退出上下文时调用,可以处理异常或资源。

例如,文件对象的 open 函数返回一个文件对象,这个对象实现了 __enter__() 和 __exit__() 方法:

with open('file.txt', 'r') as f:    # 代码块执行...

当 with 语句结束时,f.close() 会自动被调用,无论是否发生异常。


4. 实际应用案例

1. 没有异常发生时的示例

class Test:    def __enter__(self):        print('__enter__() is call!')        return self    def dosomething(self):        print('dosomethong!')    def __exit__(self, exc_type, exc_value, traceback):        print('__exit__() is call!')        print(f'type: {exc_type}')        print(f'value: {exc_value}')        print(f'trace: {traceback}')        print('__exit__() is call!')with Test() as sample:    sample.dosomething()

执行结果:

__enter__() is call!dosomethong!__exit__() is call!type: Nonevalue: Nonetrace: None__exit__() is call!

2. 异常发生时的示例

class Test:    def __enter__(self):        print('__enter__() is call!')        return self    def dosomething(self):        x = 1 / 0        print('dosomethong!')    def __exit__(self, exc_type, exc_value, traceback):        print('__exit__() is call!')        print(f'type: {exc_type}')        print(f'value: {exc_value}')        print(f'trace: {traceback}')        print('__exit__() is call!')with Test() as sample:    sample.dosomething()

执行结果:

__enter__() is call!Traceback (most recent call last):  File "
", line 1, in
File "
", line 10, in dosomethingZeroDivisionError: division by zero__exit__() is call!type:
value: division by zerotrace:
__exit__() is call!

3. 抑制异常的示例

如果 __exit__() 返回 True,异常将被抑制:

class Test:    def __enter__(self):        print('__enter__() is call!')        return self    def dosomething(self):        x = 1 / 0        print('dosomethong!')    def __exit__(self, exc_type, exc_value, traceback):        print('__exit__() is call!')        print(f'type: {exc_type}')        print(f'value: {exc_value}')        print(f'trace: {traceback}')        print('__exit__() is call!')        return Truewith Test() as sample:    sample.dosomething()

执行结果:

__enter__() is call!__exit__() is call!type: 
value: division by zerotrace:
__exit__() is call!

5. 总结

with 语句通过自动管理资源和异常,简化了文件操作和其他资源管理的代码。它的核心原理在于上下文管理器,确保在各种情况下都能妥善处理资源。

如果你对 with 语句的原理或实际应用还有疑问,可以通过实践代码进一步探索!

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

你可能感兴趣的文章
python--高级应用总结
查看>>
python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
查看>>
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>
Python写表情包搜索工具(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Python-【1】配置
查看>>
Python-从子文件夹执行绝对导入
查看>>
Python-刷新页面,直到元素可单击
查看>>