Python with statement for file Operations Guide _python

Source: Internet
Author: User

Because there is always a project to open the file, and then use Pickle.load (file), and then process ... Finally to close the file, so feel a little cumbersome, the code is not concise. So look for solutions to Python with statement.

See an article on the Internet: Http://effbot.org/zone/python-with-statement.htm is introduced with, reference to the example to understand.

If you often have such a number of code snippets, you can use several methods to improve:

Code Snippets:

Set thing up
try: Does
  something
except:
  handle Exception
finally:
  tear thing down

Case 1:

If you want to implement this function now, you open the file, read the data from the file, print it to the terminal, and then close the file.

Logically, you can extract the "Print to Terminal" As a data Processing section, you should be able to separate as a function. Other like open, close the file should be together.

File name: For_test.txt

Method 1:

Use a function to extract the public parts.

#!/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< c15/> #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 () 


Method 2:

Use yield to implement a generator that produces only one item. Loop through for-in.

The code snippet is as follows:

#yield Solution 
def controlled_execution (): 
  f = None 
  try: 
    f = open (filename, ' r ') 
    thing = F.read () c6/> #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) 

Method 3:

A class is added with the with implementation.

The code snippet is as follows:

#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) 
 

Method 4:

Implemented with the with. However, there is no exception handle function.

Def test4 (): 
  with open (filename, ' r ') as F: 
    output (F.read ()) 
 
  print F.read () 

The last print is used to test whether F has been closed.

    Finally, the purpose of writing this article is to be stimulated by one sentence: "Use the good features of language, do not use those bad features"! Python really has a lot of very elegant good features, the road long its repair far XI, I will go up and down and search ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.