由于之前有一個項目老是要打開文件,然后用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真是有很多很優雅的好特性,路漫漫其修遠兮,吾將上下而求索。。。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
