with as用法 --Python
2024-08-31 13:57:51
有些任务,可能事先设置,时候做清理工作,如下面一段程序:
f = open('tmp.txt')
data = f.read()
print(data)
是不是忘了什么?没错,很明显忘记关闭文件句柄。另外,对文件读取可能发生的异常在程序中没有做任何处理。下面使用 try except finally来处理,
f = open('tmp.txt')
try:
data = f.read()
print(data)
except BaseException as msg:
print(msg)
finally:
f.close()
虽然这段代码运行良好,但太过冗长,这里使用 with as 来写是这样的,
with open('tmp.txt') as f:
data = f.read()
print(data)
最新文章
- input框中的name和id的区别
- CnBlog客户端Windows Live Write安装方法
- vector 初始化所有方法
- Servlet Listener
- EL表达式介绍
- 【Mood-18】github 使用指南
- java thread reuse(good)
- SSAS系列——【02】多维数据(维度对象)
- GCD &;amp;&;amp; Run Loops学习笔记
- oracle中的DECODE
- 《JavaScript网页特效经典300例-进阶篇》
- Ubuntu14.04桌面系统允许root登录
- Linux解决MySQL-python安装失败问题
- Virtual Box下虚拟机复制后ip地址重复
- ES6 Module export与import复合使用
- access数据库之cookie注入
- Java 中初始化 List 集合的 6 种方式!
- fiddler 抓取 安卓模拟器 https包
- freebsd配置ip 网关 子网掩码 DNS
- 【转】netty源码分析之LengthFieldBasedFrameDecoder
热门文章
- 洛谷P2305 [NOI2014]购票 [DP,树状数组]
- meshing-做类似ICEM的Y型剖分
- LeetCode 第 152 场周赛
- 如何实现数组与List的相互转换
- 网络中的tarpit/tar pit
- TortoiseSVN 使用教程
- 临界区代码 critical section Locks and critical sections in multiple threads
- CV1——学习笔记
- Ionic4.x 中的 UI 组件(UI Components)表单相关组件
- javascript——语法 &;&; 结构