Python with statement for file operations guide,
Because a previous project always needs to open the file, and then use pickle. load (file) to process it... Finally, close the file, so it is a bit complicated and the code is not concise. Therefore, seek a solution from python with statement.
I have read an article on the Internet: http://effbot.org/zone/python-with-statement.htmwhich introduces with. I have understood it by referring to the example.
If there are such code segments, you can use the following methods to improve them:
Code segment:
set thing uptry: do somethingexcept : handle exceptionfinally: tear thing down
Case 1:
If you want to implement this function now, you can open the file, read data from the file, print the data to the terminal, and then close the file.
Logically speaking, you can extract "print to terminal" as the data processing part and use it as a function independently. Other files such as opening and closing should be the same.
File Name: for_test.txt
Method 1:
Use functions to extract 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 #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 generates 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() #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:
Add the with implementation as a class.
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:
Use. However, exception handle is not supported.
def test4(): with open(filename, 'r') as f: output(f.read()) print f.read()
The last print statement is used to test whether f has been disabled.
Finally, the purpose of writing this article is to be stimulated by a single sentence: "Use good language features, do not use those bad features "! Python has a lot of elegant features. It's a long way to go, so I will go up and down...