有些任务,可能事先设置,时候做清理工作,如下面一段程序:

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)

最新文章

  1. input框中的name和id的区别
  2. CnBlog客户端Windows Live Write安装方法
  3. vector 初始化所有方法
  4. Servlet Listener
  5. EL表达式介绍
  6. 【Mood-18】github 使用指南
  7. java thread reuse(good)
  8. SSAS系列——【02】多维数据(维度对象)
  9. GCD && Run Loops学习笔记
  10. oracle中的DECODE
  11. 《JavaScript网页特效经典300例-进阶篇》
  12. Ubuntu14.04桌面系统允许root登录
  13. Linux解决MySQL-python安装失败问题
  14. Virtual Box下虚拟机复制后ip地址重复
  15. ES6 Module export与import复合使用
  16. access数据库之cookie注入
  17. Java 中初始化 List 集合的 6 种方式!
  18. fiddler 抓取 安卓模拟器 https包
  19. freebsd配置ip 网关 子网掩码 DNS
  20. 【转】netty源码分析之LengthFieldBasedFrameDecoder

热门文章

  1. 洛谷P2305 [NOI2014]购票 [DP,树状数组]
  2. meshing-做类似ICEM的Y型剖分
  3. LeetCode 第 152 场周赛
  4. 如何实现数组与List的相互转换
  5. 网络中的tarpit/tar pit
  6. TortoiseSVN 使用教程
  7. 临界区代码 critical section Locks and critical sections in multiple threads
  8. CV1——学习笔记
  9. Ionic4.x 中的 UI 组件(UI Components)表单相关组件
  10. javascript——语法 && 结构