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获取Linux系统的各种信息
Jul 10 Python
在Python的Flask框架中使用日期和时间的教程
Apr 21 Python
Python中设置变量访问权限的方法
Apr 27 Python
Python中for循环和while循环的基本使用方法
Aug 21 Python
实例讲解Python的函数闭包使用中应注意的问题
Jun 20 Python
win8下python3.4安装和环境配置图文教程
Jul 31 Python
Python变量类型知识点总结
Feb 18 Python
Python OOP类中的几种函数或方法总结
Feb 22 Python
python字符串中匹配数字的正则表达式
Jul 03 Python
Python中if有多个条件处理方法
Feb 26 Python
Django 解决新建表删除后无法重新创建等问题
May 21 Python
python报错TypeError: ‘NoneType‘ object is not subscriptable的解决方法
Nov 05 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
《DOTA3》开发工作已经开始 《DOTA3》将代替《DOTA2》
2021/03/06 DOTA
php Static关键字实用方法
2010/06/04 PHP
CI框架学习笔记(二) -入口文件index.php
2014/10/27 PHP
Laravel框架实现利用监听器进行sql语句记录功能
2018/06/06 PHP
让getElementsByName适应IE和firefox的方法
2007/09/24 Javascript
使用jQuery操作Cookies的实现代码
2011/10/09 Javascript
js改变img标签的src属性在IE下没反应的解决方法
2013/07/23 Javascript
js 判断图片是否加载完以及实现图片的预下载
2014/08/14 Javascript
jQuery通过点击行来删除HTML表格行的实现示例
2014/09/10 Javascript
AngularJS学习笔记之TodoMVC的分析
2015/02/22 Javascript
JavaScript实现单击下拉框选择直接跳转页面的方法
2015/07/02 Javascript
jQuery实现的文字hover颜色渐变效果实例
2016/02/20 Javascript
基于socket.io+express实现多房间聊天
2016/03/17 Javascript
VUE简单的定时器实时刷新的实现方法
2019/01/20 Javascript
微信小程序自定义组件传值 页面和组件相互传数据操作示例
2019/05/05 Javascript
node.js文件操作系统实例详解
2019/11/05 Javascript
微信小程序拖拽排序列表的示例代码
2020/07/08 Javascript
JavaScript之scrollTop、scrollHeight、offsetTop、offsetHeight等属性学习笔记
2020/07/15 Javascript
python基础教程之五种数据类型详解
2017/01/12 Python
vscode 远程调试python的方法
2017/12/01 Python
Python数据类型之String字符串实例详解
2019/05/08 Python
使用 Supervisor 监控 Python3 进程方式
2019/12/05 Python
Python之Django自动实现html代码(下拉框,数据选择)
2020/03/13 Python
Django模型验证器介绍与源码分析
2020/09/08 Python
解决pytorch 数据类型报错的问题
2021/03/03 Python
选购世界上最好的美妆品:Cult Beauty
2017/11/03 全球购物
UGG澳洲官网:UGG Australia
2018/04/26 全球购物
婚纱摄影师求职信范文
2014/04/17 职场文书
副校长竞聘演讲稿
2014/09/01 职场文书
教师学期个人总结
2015/02/11 职场文书
2015年“公民道德宣传日”活动方案
2015/05/06 职场文书
2015年高三教学工作总结
2015/07/21 职场文书
初中团委工作总结
2015/08/13 职场文书
2016年五一促销广告语
2016/01/28 职场文书
高考满分作文赏析(2篇)
2019/08/12 职场文书
MySQL中distinct和count(*)的使用方法比较
2021/05/26 MySQL