Python exceptions and files in the Python Learning Manual

In the last article, we introduced Python's functions and modules, and now we introduce exceptions and files in Python.

To view the previous article, please click: https://www.cnblogs.com/dustman/p/9963920.html

Exceptions and documents

abnormal

Exceptions are also called exceptions. You've seen exceptions in previous articles. When program running errors occur, such as incorrect calls and code irregularities. When something unexpected happens to your program, it will happen and stop running.
The following code divides 5 by 0 to produce a ZeroDivision Error exception.

num1 = 5 
num2 = 0
print(num1/num2)

Operation results:

>>>
ZeroDivisionError: division by zero
>>>

Different causes lead to different anomalies, generally:
ImportError: Introduce module errors, usually without modules.
IndexError: The reading list is beyond the index range.
NameError: Use undeclared variables.
SyntaxError: Code syntax error.
TypeError: When an operation or function handles an inappropriate type.
ValueError: Built-in operation or function that receives the correct type but incorrect value.

Python also has several other built-in exceptions, such as Zero Division Error and OSError. Third-party libraries often define their own exceptions.

exception handling
We use try/except statements to capture exceptions that occur while the program is running.
The try block is used to contain blocks of code that may produce exceptions. If the exception try block stops running, the code in the except block starts to execute. If the program runs normally, the code in the except block will not execute.

try:
 num1 = 5
 num2 = 0
 print(num1/num2)
 print("Done!")
except ZeroDivisionError:
 print("Has a error")
 print("due to zero division")

Operation results:

>>>
Has a error
due to zero division
>>>
In the example above, the except statement defines ZeroDivision Error exception capture.

The try statement can have multiple except definition statements to handle exceptions. Multiple exceptions can also be captured using an except block.

try:
 var = 5
 print(var + "string!")
 print(var/2)
except ZeroDivisionError:
 print("Divided by zero!")
except (ValueError,TypeError):
 print("Has a error!")

Operation results:

>>>
Has a error!
>>>

The except statement catches all exceptions if it does not declare the exception to be paved. We should be careful to use this exception handling method, which captures unexpected errors but hides programming errors.

try:
 var = 5
 print(var + "string!")
 print(var/2)
except:
 print("An error occurred")

Operation results:

>>>
An error occurred
>>>
This exception handling method is usually used to process user input.

Final statement
Suppose you are reading a document. You should make sure that the file object is closed correctly, regardless of whether an exception occurs.
To ensure that the code eventually runs regardless of whether or not an exception occurs, we can use the final statement. Final is placed after the try/except statement.

try:
 str = "Hello"
 var = 5
 print(str)
 print(var/0)
except ZeroDivisionError:
 print("Divided by zero")
finally:
 print("This code will run no matter what")

Operation results:

>>>
Hello
Divided by zero
This code will run no matter what
>>>

What will the following code output?

try:
 print(1)
except:
 print("a")
finally:
 print("Hello")

Operation results:

>>>
1
Hello
>>>

The final statement will eventually be executed regardless of the preceding exception, including the exception generated in the except statement.

try:
 print(1)
 print(5/0)
except ZeroDivisionError:
 print(Error_var)
finally:
 print("This is executed last!")

Operation results:

>>>
1
This is executed last!
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
NameError: name 'Error_var' is not defined
>>>

throw
Use raise statement to throw an exception

print(1)
raise ZeroDivisionError
print(5)

Operation results:

>>>
1
ZeroDivisionError
>>>
You need to declare the exception name you want to throw.

The exception thrown can be used as a parameter to indicate what the error is.

age = 12
raise TypeError("Invalid type!")

Operation results:

>>>
TypeError("Invalid type!")
>>>

In the except block, the raise statement can re-throw the captured exception without declaring the name of the exception.

try:
 num= 5/0
except:
 print("Has a error")
 raise 

Operation results:

>>>
ZeroDivisionError: division by zero

Has a error
>>>

Assertion
Python's assertion is to detect a condition. If the condition is true, it does nothing, if the false triggers an error message.
The assertion can be turned on or off. Assertions are declared using assert statements.

print(1)
assert 1 + 2 == 3
print("Yes")
assert 1 + 1 == 0
print("Yes")

Operation results:

>>>
1
Yes
AssertionError
>>>
Programmers usually place assertions at the beginning of a function to check for valid input and after a function call to check for valid output.
Assertions can be turned off at run by adding - O or - OO options.

What does the following code print out?

print(1)
assert 1 != 2
print(2)
assert True
print(3)
assert False
print(4)
assert 1 + 1 == 2
print(5)

Operation results:

>>>
1
2
3
AssertionError
>>>

The second parameter of the assertion can be used as a parameter for Assertion Error.

num = 5
assert (num <= 0),"The num is bigger than zero"

Operation results:

>>>
AssertionError: The num is bigger than zero
>>>
AssertionError exceptions can be caught and processed using try/except statements like any other exceptions, and if the program does not handle them, this type of exception will terminate the program.

File processing

Open file
Reading and writing files is the most common IO (input and output) operation. Python has built-in functions for reading and writing files. To read and write files, you need to open a file object and use the open function.
The object opened by the open function is collectively called file-like Object in Python. In addition to files, they can also be byte streams of memory, network streams, custom streams, and so on.

f = open("test.txt")
Note: The parameter of the open function is the path of the file. If the file and the program are in the same directory, you can use the file name directly without specifying the path.

You can use the second parameter of the open function to specify the mode of opening the file.

# read mode
open("test.txt", "r")
open("test.txt")

# write mode
open("test.txt", "w")

# binary write mode
open("test.txt", "wb")

Open the list of file modes:

Special note: When using the "w" mode, if the file already exists, it will erase all the contents of the old file.

The close method should be used to close the file after it is opened.

f = open("test.txt","w")
# close the file
f.close()
Next we will read and write the file.

read file
Files opened with the open method can be read in read mode.

f = open("test.txt","r")
content = f.read()
print(content)
f.close()
Print all the contents of the file named "test.txt".

To read a certain number of file contents, you can use a number as a parameter to call the read function. This number determines how many bytes to read.
You can make multiple read calls to the same file object, which reads the contents of the file. In the absence of parameters, the read function returns the rest of the file.

f = open("test.txt","r")
print(f.read(32))
print(f.read(16))
print(f.read(8))
print(f.read())
f.close()

When all content is read, the read function is called to return an empty string.

f = open("test.txt","r")
f.read()
print("reading")
print(f.read())
print("finished!")
f.close()

Operation results:

>>>reading

finished!
>>>

Open a file to read its content and print the length of the content.

f = open("test.txt","r")
str = f.read()
print(len(str))
f.close()

Operation results:

>>>
16
>>>

To read one line at a time, we can use the readline method, and also use readlines to read all the content at once and return a list, each element in the list represents one line of content.

f = open("test.txt","r")
print(f.readlines())
f.close()

Running results:

>>>
['I like Python!!!']
>>>

Use the for statement to traverse each line of the file:

f = open("test.txt","r")
for line in f:
 print(line)
f.close()

Operation results:
>>>
Line 1 : Hello world!

Line 2 : I like Python!

Line 3 : I like Java!
>>>

In output, the returned line contains newline characters, and the print function automatically adds new lines at the end of the output.

Writing file
Write the content into the file using the write method.

f = open("test.txt","w")
f.write("I am happy!")
f.close()

f = open("test.txt","r")
print(f.read())
f.close()

Operation results:

>>>
I am happy!
>>>
If the file does not exist, "w" will create a file.

In write mode, if a file exists, it will clear all content and write new content to the file.

f = open("test.txt","r")
print("Reading...")
print(f.read())
print("Finished!")
f.close()

f = open("test.txt","w")
f.write("New text")
f.close()

f = open("test.txt","r")
print("Reading new contents")
print(f.read())
print("Finished!")
f.close()

Operation results:

>>>
Reading...
I am happy!
Finished!
Reading new contents
New text
Finished!
>>>
Special attention: the original document will be rewritten by new content.

If write is successful, the method returns the number of bytes written.

msg = "I like Python!!!"
f = open("test.txt","w")
count = f.write(msg)
print(count)
f.close()

Operation results:

>>>
16
>>>

Read and write files
It is a good programming habit to ensure that files are always closed after use and to avoid wasting resources. We use try / final statements.

try:
 f = open("test.txt")
 print(f.read())
finally:
 f.close()
It also ensures that the file object is closed correctly when an exception occurs.

It's too cumbersome to close files like this every time. So Python introduced the with statement to help us call the close() method automatically.

with open("test.txt") as f:
print(f.read())
It's a good habit to open a file with a with statement. Even if there are exceptions, the with statement will automatically close the file handle for us.

 

 

 

"It's a good feeling to run madly in one direction."

Keywords: Python Programming network REST

Added by melittle on Thu, 16 May 2019 13:10:13 +0300