import sys
print(sys.path)
- 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
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)
- 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)
- 1.os.path.dirname(file)
- Not recommended for use
# Get the directory of the file
dir_name = os.path.dirname(__file__)
print(dir_name)
- 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)
Example : Suppose you need to open another package pac01 Under the demo.txt
1. Ideas
1. Get the absolute path of the current file
2. Get the directory path of the current file
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())
1.os.getcwd(): Get the current working directory
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()
print(os.listdir())
6.os.path.isfile()
7.os.path.isdir
print(os.path.isfile(__file__))
print(os.path.isdir(__file__))
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
2. Throw him raise
1. Abnormal capture
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
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 :
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
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
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
"""
- 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
- 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 """
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 ~~~