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

首頁 > 編程 > Python > 正文

python with statement 進行文件操作指南

2019-11-25 18:16:29
字體:
來源:轉載
供稿:網友

由于之前有一個項目老是要打開文件,然后用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() 

 最后一句print是用來測試f是否已經被關閉了。

    最后總結一下,寫這篇文章的目的主要是受了一句話的刺激:“使用語言的好特性,不要使用那些糟糕的特性”!python真是有很多很優雅的好特性,路漫漫其修遠兮,吾將上下而求索。。。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福建省| 朝阳区| 贺州市| 沾化县| 隆德县| 呼伦贝尔市| 扶余县| 垣曲县| 郧西县| 清远市| 中卫市| 门头沟区| 玉田县| 都安| 河北区| 高清| 韶山市| 建瓯市| 前郭尔| 凤山县| 舟曲县| 敦化市| 若羌县| 浦江县| 建始县| 若尔盖县| 榆社县| 蛟河市| 台安县| 四子王旗| 灵璧县| 巴彦县| 宜宾市| 成武县| 策勒县| 湖州市| 荥经县| 德江县| 田东县| 安溪县| 汽车|