由于之前有一個項目老是要打開文件,然后用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()
新聞熱點
疑難解答