[Learn Python with me] python with statement advanced understanding, pythonstatement

Source: Internet
Author: User

[Learn Python with me] python with statement advanced understanding, pythonstatement

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 up

Try:

Do something

Except t:

Handle exception

Finally:

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.

Python code
  1. #! /Usr/bin/env python
  2. From _ future _ import with_statement
  3. Filename = 'for_test.txt'
  4. Def output (content ):
  5. Print content
  6. # Functio solution
  7. Def controlled_execution (func ):
  8. # Prepare thing
  9. F = None
  10. Try:
  11. # Set thing up
  12. F = open (filename, 'R ')
  13. Content = f. read ()
  14. If not callable (func ):
  15. Return
  16. # Deal with thing
  17. Func (content)
  18. Handle t IOError, e:
  19. Print 'error % s' % str (e)
  20. Finally:
  21. If f:
  22. # Tear thing down
  23. F. close ()
  24. Def test ():
  25. Controlled_execution (output)
  26. Test ()

 

Method 2:

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

The code snippet is as follows:

Python code
  1. # Yield solution
  2. Def controlled_execution ():
  3. F = None
  4. Try:
  5. F = open (filename, 'R ')
  6. Thing = f. read ()
  7. # For thing in f:
  8. Yield thing
  9. Handle t IOError, e:
  10. Print 'error % s' % str (e)
  11. Finally:
  12. If f:
  13. F. close ()
  14. Def test2 ():
  15. For content in controlled_execution ():
  16. Output (content)

 

Method 3:

Add the with implementation as a class.

The code snippet is as follows:

Python code
  1. # Class solution
  2. Class controlled_execution (object ):
  3. Def _ init _ (self ):
  4. Self. f = None
  5. Def _ enter _ (self ):
  6. Try:
  7. F = open (filename, 'R ')
  8. Content = f. read ()
  9. Return content
  10. Handle t IOError, e:
  11. Print 'error % s' % str (e)
  12. # Return None
  13. Def _ exit _ (self, type, value, traceback ):
  14. If self. f:
  15. Print 'Type: % s, value: % s, traceback: % s' % \
  16. (Str (type), str (value), str (traceback ))
  17. Self. f. close ()
  18. Def test3 ():
  19. With controlled_execution () as thing:
  20. If thing:
  21. Output (thing)

 

Method 4:

Use. However, exception handle is not supported.

Python code
  1. Def test4 ():
  2. With open (filename, 'R') as f:
  3. Output (f. read ())
  4. 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...


How can I learn Python directly in this case?

C is not a high-level language, not an object oriented, but also a static typed language. python is a high-level language, an object oriented, or a dynamic typed language. The two are quite different in syntax. python is much simpler. However, the syntax in programming is very secondary. If you learn python, instead of C, you can focus on your thoughts, it's not a waste of remembering the cumbersome syntax and having no creativity.

How can I use python to learn the web path of gis?

For me, I have some experience. For gis, python can be used to write some gis tools. These tools are generally used together with the arcgis toolbox. for gis alone, there are not many things in python, but there is no need to associate it with learning webgis in three dimensions. Therefore, if you want to learn more things, you can consider python. If you have limited energy, you can do whatever you want, my personal feelings.

Related Article

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.