With ... as ...

Source: Internet
Author: User
Tags file handling

There are some tasks that may need to be set up beforehand to do cleanup work afterwards. For this scenario, Python's with statement provides a very convenient way to handle it. A good example is file handling, where you need to get a file handle, read the data from the file, and then close the file handle.

The With-as expression greatly simplifies the work of writing finally every time.

When working with files, you can write the following very concise way. The important thing is that you don't have to think about when to fclose the problem.

With open ("/tmp/foo.txt") as file:    = File.read ()

It is important to note that the code behind the elegance must be something that has already been done. Now that the file handle is inside this class, you have completed the work like enter and finally.

Reference:

Http://blog.kissdata.com/2014/05/23/python-with.html

With ... as ...

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.