国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python with statement 進行文件操作指南

2020-02-23 05:41:09
字體:
來源:轉載
供稿:網友

由于之前有一個項目老是要打開文件,然后用pickle.load(file),再處理。。。最后要關閉文件,所以覺得有點繁瑣,代碼也不簡潔。所以向python with statement尋求解決方法。

在網上看到一篇文章:http://effbot.org/zone/python-with-statement.htm是介紹with 的,參考著例子進行了理解。

如果經常有這么一些代碼段的話,可以用一下幾種方法改進:

代碼段:

set thing uptry:  do somethingexcept :  handle exceptionfinally:  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()             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 前郭尔| 荣昌县| 泰来县| 莱阳市| 宝山区| 文成县| 秦安县| 三门峡市| 长子县| 新和县| 济南市| 辉南县| 大冶市| 泸西县| 饶阳县| 封开县| 同心县| 吉木萨尔县| 德庆县| 垦利县| 石家庄市| 沧源| 抚州市| 广元市| 惠东县| 仁布县| 平舆县| 洛浦县| 卓资县| 南溪县| 红原县| 喀喇| 九龙坡区| 前郭尔| 商南县| 简阳市| 长阳| 蒙城县| 绥棱县| 泸州市| 高邑县|