程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python -- exception handling, assertion and path handling, simple and clear version

編輯:Python

1. Path processing

1. Find module :sys.path

import sys
print(sys.path)

- 1. understand

 - 1. yes python To find packages or modules
- 2. Project start root directory ,python Built in directory
- 3. Although I say python The modules we wrote can also be stored in the installation directory of , But not recommended ( That's too much , It's not easy to find )
- 4. If you find that the module cannot be imported in the future , You can use sys.path
- 5. It returns an array
- 6. When using, you need to import sys:import sys
- python The catalog of , It is mainly used in external libraries , Or third-party modules

- 2. There are two ways to guide the package

python Exchange of learning Q Group :903971231####
- 1.from..module ...import Method 、 Variable etc.
- from python_basic.class10_ route .pac01.module_012 import a
print(a)
print(sys.path)
- 2.from pac ... import module
- from python_basic.class10_ route .pac01 import module_012
print(module_012.a)
print(sys.path)

2. Get the path of the file

  • 1. Get absolute path os.path.abspath(file)
 - import os
# Get absolute path 
# Fixed way of writing 
# file Indicates the name of the running file 
abs_path=os.path.abspath(file)
print(abs_path)
import os
# Absolute path to the current file 
abs_path=os.path.abspath(__file__)
print(abs_path)

- 2. Get the directory path of the file

 - 1.os.path.dirname(file)
- Not recommended for use
# Get the directory of the file 
dir_name = os.path.dirname(__file__)
print(dir_name)

- 2.os.path.dirname(abs_path)

- Suggest using
 - dir_name1 =os.path.dirname(file)
dir_name =os.path.dirname(abs_path)
abs_path =os.path.abspath(__file__)
dir_name =os.path.dirname(abs_path)
print(dir_name)

- 3. Application scenarios

  • Example : Suppose you need to open another package pac01 Under the demo.txt

  • 1. Ideas

    • 1. Get the absolute path of the current file

      • abs_path=os.path.abspath(file)
    • 2. Get the directory path of the current file

      • dir_name =os.path.dirname(abs_path)
    • 3. Directory path and... Of the current file pac01 Splicing

      • 1. Recommended approach

        • txt_file_path=os.path.join(dir_name,“pac01”,“demo.txt”)

        • PS Generally speaking , It is to obtain the following path of the project through a certain file

abs_path = os.path.abspath(__file__)
dir_name =os.path.dirname(abs_path)
txt_file_path=os.path.join(dir_name,"pac01","demo006.txt")
with open(txt_file_path,encoding="utf-8") as f:
print(f.readlines())

 - 2. Other methods : Not recommended for use
python Exchange of learning Q Group :903971231###
- # print(dir_name+'/pac01/demo.txt')
# print(dir_name+r'\pac01\demo.txt')
- This way of writing is not recommended , Because different systems ,windows It's usually \,mac yes /, Change to change trouble
- 4. Open the file and read
- with open(txt_file_path,encoding="utf8") as f:
print(f.read())
  • PS: When getting file path , The path or file does not have to exist , Understand this

3. working directory

  • 1.os.getcwd(): Get the current working directory

    • 1. In which directory do you run python Program , Which path is output
print(os.getcwd())

  • 2.os.chdir(): Switch working directory

  • 3.os.mkdir(“test_dir”)

    • Create a working directory

    • os.mkdir(“test_dir”)

  • 4.os.rmdir()

    • Delete the working directory

    • os.rmdir(“test_dir”)

  • 5.listdir()

    • Get the directory list under the current path , Return data in list format
print(os.listdir())

  • 6.os.path.isfile()

    • Determine whether the current file is a file , Returns a Boolean value
  • 7.os.path.isdir

    • Determine whether the current file is a directory , Returns a Boolean value
print(os.path.isfile(__file__))
print(os.path.isdir(__file__))

2. exception handling

1. Abnormal understanding

  • 1. If the program encounters an exception , No more execution

  • 2. People who write code can't let a program terminate when it encounters an exception

    • 1. Capture him catch

      • Change the abnormal behavior encountered by the program , exception handling , I hope the program doesn't terminate , Do as I say , It is called exception capture
    • 2. Throw him raise

2. exception handling

  • 1. Abnormal capture

    • 1. Basic writing :

try:

The code you want to execute that may cause exceptions

except:

After an exception occurs in the program , What you want the program to do

- 1. Program first try Code in
- 2. But once try An error is reported in one of the codes , Will execute jump to except,try The rest of the code will not execute
- 3. Example :
- 1.except Captured
try:
print(" Running code ")
a = 1 / 0
print(f" The result of the calculation is :{
a}")
except:
print("1 Can't divide 0, You need to change the divisor ")
print(" Other programs ")

The output is zero :

“”"

 - 2. Exception type capture
- 1. This type of situation is not captured
- # try:
try:
print(" Running code ")
a=1/0
print(f" The result of the calculation is :{
a}")
except IndexError:
print("1 Can't divide 0, You need to change the divisor ")
print(" Other programs ")
# Only print Running code , Because of the wrong report , Unable to capture ZeroDivisionError abnormal ,

 - 2. Caught this type of error
try:
print(" Running code ")
a=1/0
print(f" The result of the calculation is :{
a}")
except ZeroDivisionError:
print("1 Can't divide 0, You need to change the divisor ")
print(" Other programs ")

The output is zero :

  • 3. Print exception information Exception( Or some kind of error report ) as e

    - 1. Single exception
    - # Print exception information , Generally use this method
    
try:
print(" Running code ")
a=1/0
print(f" The result of the calculation is :{
a}")
except ZeroDivisionError as e:
print(e)
print(" Other programs ")

The output is zero :


 - 2. Multiple abnormal
try:
lst = ['yz', 'addd']
lst[3]
a=1/0
except ZeroDivisionError as err:
print(err)
print("hello word")
# IndexError: list index out of range
 - # When capturing multiple

Method 1:

try:
{
"name":"zhangsan","age":18}['name1']
lst = ['yz', 'addd']
lst[3]
a=1/0
except (ZeroDivisionError,IndexError,KeyError) as err:
print(err)
print("hello word")

Printed results :

Method 2

try:
a = 1 / 0
{
"name":"zhangsan","age":18}['name1']
lst = ['yz', 'addd']
lst[3]
except ZeroDivisionError as err:
print(err)
print("ZeroDivisionError")
# Catch this anomaly 
# division by zero
# ZeroDivisionError
except IndexError:
print("IndexError")
# Catch this anomaly IndexError
except KeyError:
print("KeyError")
# Catch this anomaly KeyError

Printed results :

 - Which one to use , According to the actual situation
  • 2.try…finally

    • 1.finally After the code whether normal or not , It will be carried out

      • 1. natural
try:
1/1
print(" Normally executed code ")
except ZeroDivisionError as e:
print(" You can't divide by 0")
finally:
print(" Whether it's normal or not , Code that will execute ")

Printed results :


 - 2. Anomalous
try:
1/0
print(" Normally executed code ")
except ZeroDivisionError as e:
print(" You can't divide by 0")
finally:
print(" Whether it's normal or not , Code that will execute ")

Printed results :

- 2. Common applications are after opening a file ,** Close file **
- # hypothesis demo.py Was opened
import io
try:
f=open("demo.py",'a')
f.read()
except io.UnsupportedOperation as e:
print(" File read failed ")
print(e)
finally:
f.close()
"""

Print the results :

File read failed

not readable

“”"

  • 2. Throw exception

    • Example 1:
def adult_add(a,b):
""" Two greater than or equal to 18 Add up the number of ; Less than 18 Of cannot be added """
if (a<18) or (b<18):
raise ValueError(" Parameter must be greater than or equal to 18")
c=a+b
return c
adult_add(18,19)
adult_add(3,4) #ValueError: Parameter must be greater than or equal to 18
print(" The function is finished ")
"""

Print the results :

 File ".../demo03_raise.py", line 13, in adult_add
raise ValueError(" Parameter must be greater than or equal to 18")
ValueError: Parameter must be greater than or equal to 18
"""
  • 2. Call... Based on the previous example :
 - try:
adult_add(3, 4) # ValueError: Parameter must be greater than or equal to 18
except:
print(" The function is finished ")
# Print the results : The function is finished 
  • 3. Scenarios that can be used for assertions

3. Assertion

1. understand

- 1.assert Followed by a conditional statement , If the condition does not hold, the condition exception will be triggered
- 2. grammar :assert Conditional expression
### 3. Example 
- height=int(input(" Please enter height :"))
assert height>180
# When the assertion is true : Please enter height :181
""" When the assertion is false : Please enter height :180 Traceback (most recent call last): File ".../demo04_assert.py", line 9, in assert height>180 AssertionError """

Last

This is the end of today's article , Remember to praise your favorite friends . Remember to ask questions about this article at any time

yo !!! See you next time ~~~


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved