Python notes (iv): Exception handling mechanism with open ()

Source: Internet
Author: User

(a) Overview of exception handling mechanisms

Just as there are unexpected situations in your daily life (for example: You might have thought about what 500w would do if you did), and the code ran into this kind of unexpected situation, and Python provided a mechanism to handle the unexpected (just like if you had 5 million of what you want the code to do).

Note: Without handling this unexpected situation, the code crashes and all subsequent code stops running.

In practical applications, it is divided into 3 main steps:

(1) Circle the code that you think might be out of the ordinary.

(2) Set the type of exception that you think you can ignore.

(3) When an exception occurs, the way you want to handle it.

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

(ii) Open

    • The open () function opens a file and creates a Document object

The_file = open (' Test. txt ')

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

Mode

Describe

R

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

Rb

Opens 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 read-write. The file pointer will be placed at the beginning of the file.

(c) Examples

(1) Create a new file test. txt, enter the following

Zhang San: It's a nice day today.

John Doe: Yes, it's really good.

Zhang San: The Sun is shining.

John Doe: Fine flowers.

Harry: Put on the scene: please bring a good helmet

Zhang San: Rare good weather, not lazy today.

John Doe: You are the only one who can say begging so tall.

Separator

Zhang San: Rare good weather, not lazy today.

John Doe: You are the only one who can say begging so tall.

(2) Use open to read the above file, combined with the exception handling mechanism to explain

Try:
The_file = open (R ' C:\Users\123456\Desktop\ test. txt ', encoding=' UTF-8 ')
for Each_line in The_file:
Try:
(Role,line_spoken) =each_line.split (":", 1)
# to: Split the data, the parameter 1 means that only 2 parts are decomposed.

#For example: Split the first row of data, that is, role = ' Zhang San ' line_spoken = The weather is really good today.
# do not set this parameter is to split as far as possible, then read Harry: Loading the scene: Please take good safety helmet data will be wrong
The valueerror exception occurs when you #分割 the "delimiter" data (because there is no:) and all data will not be read after this error is not ignored.
Print (role,end="")
Print"said"+":", end="")
Print (line_spoken,end="")
exceptValueError:
# when ValueError is present, the value of the each_line is output directly
Print (each_line,end="")
The_file.close ()
exceptIOError:
#the prompt file does not exist when the file cannot be found
Print"file does not exist! ")

(iv) Handling possible errors and errors prior to processing 2 different ways

(1) In fact, we can also deal with possible errors in advance, implemented by the following code.

Each_line.find (': ') = =-1:
The target string is returned when it is not found-1, not reversed
Else:
Print (each_line,end="")

(2) However, the problem is that you may need to write a lot of logic code to deal with this situation, so that the function code may only account for a very small part, resulting in the code to implement the function is not clear. There is no such problem through exception handling mechanism, the function of code to realize at a glance.

Python notes (iv): Exception handling mechanism with open ()

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.