python with statement 进行文件操作指南


Posted in Python onAugust 22, 2014

由于之前有一个项目老是要打开文件,然后用pickle.load(file),再处理。。。最后要关闭文件,所以觉得有点繁琐,代码也不简洁。所以向python with statement寻求解决方法。

在网上看到一篇文章:http://effbot.org/zone/python-with-statement.htm是介绍with 的,参考着例子进行了理解。

如果经常有这么一些代码段的话,可以用一下几种方法改进:

代码段:

set thing up
try:
  do something
except :
  handle exception
finally:
  tear thing down

案例1:

假如现在要实现这么一个功能,就是打开文件,从文件里面读取数据,然后打印到终端,之后关闭文件。

那么从逻辑上来说,可以抽取“打印到终端”为数据处理部分,应该可以独立开来作为一个函数。其他像打开、关闭文件应该是一起的。

文件名为:for_test.txt

方法1:

用函数,把公共的部分抽取出来。
 

#!/usr/bin/env python 
from __future__ import with_statement  
filename = 'for_test.txt' 
def output(content): 
  print content 
#functio solution 
def controlled_execution(func): 
  #prepare thing 
  f = None 
  try: 
    #set thing up 
    f = open(filename, 'r') 
    content = f.read() 
    if not callable(func): 
      return 
    #deal with thing  
    func(content) 
  except IOError, e: 
    print 'Error %s' % str(e) 
  finally: 
    if f:  
      #tear thing down 
      f.close() 
def test(): 
  controlled_execution(output) 
test()

 
方法2:

用yield实现一个只产生一项的generator。通过for - in 来循环。

代码片段如下:

#yield solution 
def controlled_execution(): 
  f = None 
  try: 
    f = open(filename, 'r') 
    thing = f.read() 
    #for thing in f: 
    yield thing 
  except IOError,e: 
    print 'Error %s' % str(e) 
  finally: 
    if f:  
      f.close() 
def test2(): 
  for content in controlled_execution(): 
    output(content)

 

方法3:

用类的方式加上with实现。

代码片段如下:
 

#class solution 
class controlled_execution(object): 
  def __init__(self): 
    self.f = None 
  def __enter__(self): 
    try: 
      f = open(filename, 'r') 
      content = f.read() 
      return content 
    except IOError ,e: 
      print 'Error %s' % str(e) 
      #return None 
  def __exit__(self, type, value, traceback): 
    if self.f: 
      print 'type:%s, value:%s, traceback:%s' % \ 
          (str(type), str(value), str(traceback)) 
      self.f.close() 
def test3(): 
  with controlled_execution() as thing: 
    if thing: 
      output(thing)

方法4:

用with实现。不过没有exception handle 的功能。

def test4(): 
  with open(filename, 'r') as f: 
    output(f.read()) 
 
  print f.read()

 最后一句print是用来测试f是否已经被关闭了。

    最后总结一下,写这篇文章的目的主要是受了一句话的刺激:“使用语言的好特性,不要使用那些糟糕的特性”!python真是有很多很优雅的好特性,路漫漫其修远兮,吾将上下而求索。。。

Python 相关文章推荐
Python Web服务器Tornado使用小结
May 06 Python
python中enumerate的用法实例解析
Aug 18 Python
Python3使用requests包抓取并保存网页源码的方法
Mar 15 Python
python画折线图的程序
Jul 26 Python
python看某个模块的版本方法
Oct 16 Python
Python pycharm 同时加载多个项目的方法
Jan 17 Python
Python命令行参数解析工具 docopt 安装和应用过程详解
Sep 26 Python
PYTHON绘制雷达图代码实例
Oct 15 Python
Python 切分数组实例解析
Nov 07 Python
TensorFlow MNIST手写数据集的实现方法
Feb 05 Python
python爬虫库scrapy简单使用实例详解
Feb 10 Python
详解tensorflow2.x版本无法调用gpu的一种解决方法
May 25 Python
Python中还原JavaScript的escape函数编码后字符串的方法
Aug 22 #Python
python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
Aug 22 #Python
Python升级提示Tkinter模块找不到的解决方法
Aug 22 #Python
Python实现多行注释的另类方法
Aug 22 #Python
Python利用pyHook实现监听用户鼠标与键盘事件
Aug 21 #Python
Python发送Email方法实例
Aug 21 #Python
Python生成验证码实例
Aug 21 #Python
You might like
php ImageMagick windows下安装教程
2015/01/26 PHP
使用xampp搭建运行php虚拟主机的详细步骤
2015/10/21 PHP
ThinkPHP项目分组配置方法分析
2016/03/23 PHP
PHP $O00OO0=urldecode & eval 解密,记一次商业源码的去后门
2020/09/13 PHP
兼容多浏览器的字幕特效Marquee的通用js类
2008/07/20 Javascript
JS下高效拼装字符串的几种方法比较与测试代码
2010/04/15 Javascript
分享一个asp.net pager分页控件
2012/01/04 Javascript
js限制checkbox选中个数以限制六个为例
2014/07/15 Javascript
深入分析js的冒泡事件
2014/12/05 Javascript
jQuery实现径向动画菜单效果
2015/07/17 Javascript
jQuery实现选中弹出窗口选择框内容后赋值给文本框的方法
2015/11/23 Javascript
js组件SlotMachine实现图片切换效果制作抽奖系统
2016/04/17 Javascript
用js实现博客打赏功能
2016/10/24 Javascript
jQuery Validate验证表单时多个name相同的元素只验证第一个的解决方法
2016/12/24 Javascript
详解jQuery中关于Ajax的几个常用的函数
2017/07/17 jQuery
vue2.0 datepicker使用方法
2018/02/04 Javascript
js实现前面自动补全位数的方法
2018/10/10 Javascript
js canvas实现画图、滤镜效果
2018/11/27 Javascript
详解微信小程序之提高应用速度小技巧
2020/01/07 Javascript
nodejs使用socket5进行代理请求的实现
2020/02/21 NodeJs
nodejs脚本centos开机启动实操方法
2020/03/04 NodeJs
Python性能优化技巧
2015/03/09 Python
Python字符串匹配算法KMP实例
2015/07/18 Python
Python编程中对super函数的正确理解和用法解析
2016/07/02 Python
scrapy爬虫实例分享
2017/12/28 Python
[原创]windows下Anaconda的安装与配置正解(Anaconda入门教程)
2018/04/05 Python
Django之无名分组和有名分组的实现
2019/04/16 Python
使用Python调取任意数字资产钱包余额功能
2019/08/15 Python
自定义Django默认的sitemap站点地图样式
2020/03/04 Python
Python CategoricalDtype自定义排序实现原理解析
2020/09/11 Python
俄罗斯皮肤健康中心:Pharmacosmetica.ru
2020/02/22 全球购物
会计助理的岗位职责
2013/11/29 职场文书
单位租房协议书范本
2014/12/04 职场文书
领导欢送会主持词
2015/07/06 职场文书
2019个人半年工作总结
2019/06/21 职场文书
Spring Boot 排除某个类加载注入IOC的操作
2021/08/02 Java/Android