Python note (4): Exception Handling Mechanism and open (), python exception handling

Source: Internet
Author: User

Python note (4): Exception Handling Mechanism and open (), python exception handling

(1) Exception Handling Mechanism Overview

Just as you may encounter various unexpected situations in your daily life (for example, you may have considered how to do this if you have million RMB), this unexpected situation will also occur during code running, python provides such a mechanism to handle unexpected situations (just like how you want code to be done if there are 5 million users ).

Note: If you do not handle this unexpected situation, the code will crash and all subsequent code will stop running.

In actual application, there are three steps:

(1) circle the code that you think may cause exceptions.

(2) set the exception type that you think can be ignored.

(3) The method you want to handle an exception.

Exception types and formats can be viewed: http://www.runoob.com/python/python-exceptions.html

(2) open

  • The open () function is used to open a file and create a file object.

The_file = open('test .txt ')

Parameters and methods can be referred to: http://www.runoob.com/python/python-func-open.html

Mode

Description

R

Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.

Rb

Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.

R +

Open a file for reading and writing. The file pointer will be placed at the beginning of the file.

 

(3) Example

(1) create a file test .txt and enter the following content

Michael Zhang: The weather is good today.

Li Si: Yes, it's really great.

Michael JACOB: The sun is shining.

Li Si: birds with flowers.

Wang Wu: loading on site: Please bring your helmet

Michael Zhang: It's rare to see good weather. Today, we will not be lazy.

Li Si: only you can say that begging is so tall.

Delimiter

Michael Zhang: It's rare to see good weather. Today, we will not be lazy.

Li Si: only you can say that begging is so tall.

(2) Use open to read the above files and use the Exception Handling Mechanism to explain

Try:
The_file = open (R 'C: \ Users \ 123456 \ Desktop \Test .txt', Encoding ='Utf-8')
 ForEach_lineInThe_file:
Try:
(Role, line_spoken) = each_line.split (":", 1)
#Split data with:. Parameter 1 indicates that only two parts are split.

#For example, split the first line of data, that is, role = 'zhang san' line_spoken = today's weather is really good.
# If this parameter is not set, it is to be split as much as possible. Therefore, when Wang Wu is read: loading the site: Please bring the security helmet data with errors
# A ValueError exception occurs when dividing the line of "separator" (because there is no :). If this error is not ignored, all subsequent data cannot be read.
Print (role, end ="")
Print ("Said"+":", End ="")
Print (line_spoken, end ="")
ExceptValueError:
#When ValueError occurs, the each_line value is output directly.
Print (each_line, end ="")
The_file.close ()
ExceptIOError:
#When the file cannot be found, the system prompts that the file does not exist.
Print ("The file does not exist! ")

 

(4) handle two possible errors and errors in advance

(1) In fact, we can also handle possible errors in advance through the following code.

If notEach_line.find (':') =-1:
# Find ()If the target string is not found,-1 and not are returned.
Else:
Print (each_line, end ="")

 

(2) but the problem is that you may need to write a large number of logic code to handle this situation, so that the functional code may only take a very small part, the functions to be implemented by the Code are unclear. This problem does not exist through the exception handling mechanism, and the functions to be implemented by the Code are clear at a glance.

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.