python with statement 進行檔案操作指南

來源:互聯網
上載者:User
由於之前有一個項目老是要開啟檔案,然後用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真是有很多很優雅的好特性,路漫漫其修遠兮,吾將上下而求索。。。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.