# Package introduction
'''
library : Provides a range of functions .
1. Built in Library / package - It can be used directly without installation , The installation path is :Lip
2. Third party Library / package - First pip Installed in use , The installation path is :Lip\site-packages
3. Custom modules / package ( Yes 2 Kind of )
a. At the same directory :import Module name
b. Relative to the project directory ( Most commonly used ):
1.import Package name . Module name
2.from Package name import Module name
3.from Package name .[ Package name . Package name ] import Module name [as Alias ]
4.from Package name .[ Package name . Package name ]. Module name import Variable name / Function name / Class name
modular :py file
package :__init__.py Folder
'''
# When you create your own custom file , Never use a library name for naming
# Get the search path :
import sys # import modular
for item in sys.path: # Traverse this
print(item) # Print
# Custom module introduces Syntax
# 1. At the same directory :import Module name
import love_py # Yes bug, Generally do not use
# 2. Relative to the project directory ( Most commonly used ):
# a.import Package name . Module name
# # b.from Package name import Module name
# os modular path Processing path
import os
# os Path to the operation ( There are three main methods )
# Memorization :os.path.abspath() and os.path.join(a,b)
# 1.os.path.abspath() Get the absolute path of the current file
re = os.path.abspath('love_py') # Or you can use . Instead of , Represents the current file
print(re)
# 2.os.path.dirname() Return file / Directory path
ks = os.path.dirname(re) # Parameter is an absolute path
print(ks)
s = os.path.dirname(ks) # In getting his upper level path
print(s)
# 3.os.path.join(a,b) The path linking the two parts , Form a complete path
# Get the project directory , The absolute path to another file
# Path splicing
res = os.path.join(s,"love_py") # Path splicing processing
print(res)
# 4.os.getcwd() Displays the current working path
y = os.getcwd()
print(y)
# 5.os.mkdir() Create a new directory under a path
# Create under the specified path
path = r'E:\Python-workspace\py30\2020-06-02- The eighth class ' # Path to create
os.mkdir(path + './fiel1') # Create a new directory
# # Create... In the current path
r = os.mkdir('list')
print(r)
# 6.os.rmdir() Delete a directory
deo = os.rmdir('fiel1')
print(deo)
# 7.os.listdir() Get the directory list under the current path , Return data in list format
po = os.listdir('.') # Get... In the current directory
print(po)
# 8.os.path.isdir() Determine whether the current file is a directory , Returns a Boolean value
pr = os.path.isdir(r'E:\Python-workspace\py30\2020-06-02- The eighth class \love_py')
print(pr)
# 9.os.path.isfile() Determine whether the current file is a file , Returns a Boolean value
to = os.path.isfile('.')
print(to)
'''
There are other things to know
os.getcwd() Displays the current working path
os.chdir() Switch the current path
os.mkdir() Create a new directory under a path
os.rmdir() Delete a directory
os.listdir() Get the directory list under the current path , Return data in list format
os.path.isdir() Determine whether the current file is a directory , Returns a Boolean value
os.path.dir() Determine whether the current file is a file , Returns a Boolean value
'''
# Magic variable :file /name
# _file_: file name (pycherm Direct runtime path )
# _name_: Module ( file ) Module name of
# ( If the file is the startup file of the program ,name The value is _main_)
# __file__ : Current filename .
# __name__ : If you are running the current file , that Its value is :__main__
# exception handling
'''
1、 First translate and report errors
2、 Find your own code , Error in the first few lines .
Document processing : file does not exist / path does not exist
Capture exception !!
In the process , Catch this anomaly , We can add our own extra code processing . And then throw an exception .
How do I know which line is going to go wrong ?
How should I know? , What exception do I want to catch ?
1. When interacting with third-party resources , Be sure to handle exceptions .
2. The issue of resource release .--- http Connect / Database connection /excel operation
try:
Code that can go wrong
except:( If something goes wrong , Get into except)
Exception caught .
The code that will be executed after the code reports an error .
[else:
try When no error is reported in the code , Code that will execute .
finally:
Whether or not there is an exception , Code that must execute .
]
If you catch an exception , And did what you wanted to do . Then throw this exception to :
raise
'''
# If the file opens successfully , Then write the data .
try:
fs = open(r"D:\Pychram-Workspace\py30\python practice .txt","r",encoding="utf-8")
# fs.write(" Successfully wrote ")
except: # Capture exception
print(" Code error !!") # I did my own thing . Output some content .
raise # Will throw exception information . Give Way python Received
else:
fs.write(" Successfully wrote ")
finally:
print(" Code that must execute !!")
try:
fs.close() # Clean up the closeout work . Code that will execute regardless of success or failure .
except:
pass # If fs.close() failed , No need to deal with it . Ignore exceptions directly .
try: fs = open(r"C:\down\day10\1- Extended learning \test.txt",'r',encoding='utf-8') except FileNotFoundError as e: # There may be FileNotFoundError error , Appear in , Execute the following pring, And alias it e, Print something like raise print(" file does not exist !") # print(e) # Print something like raise, But no raise comprehensive , Only one line will be printed raise # raise Throw an exception , It's comprehensive except KeyError: print(" Other exceptions ,key error !") except Exception: print(" Not that the file does not exist , Neither keyError, It's another mistake ")
'''
# summary :
# 1、 Use external resources , Cleaning work needs to be done .
# 2、 You want to catch exceptions , In an abnormal situation , Do something of your own .
# Module introduction : Relative to the project directory . from package import modular
# Path processing :os modular . Get absolute path .__file__ os.path.abspath(__file__)
# Get the directory os.path.dirname( Absolute path )
# Path splicing os.path.join( route 1, file name ) -- Eventually it's an absolute path .
# # exception handling : try:
# There may be unexpected code
# except:
# try There is an exception in the code in , Will execute the code here
# [else:
# try There is no exception in the code in , Then execute the code here
# finally:
# No matter what try Is there any exception in the code in , Actions that must be performed .
# In general , Cleaning work .]
'''
""" 1、 What is the syntax for exception capture ? Please list the types of errors you have encountered . 2、 Write the following program Optimize the program to buy oranges in the fresh food supermarket a. The cashier entered the price of the orange , Company : element / Jin b. The cashier enters the weight of the orange purchased by the user , Company : Jin c. Calculate and output payment amount The new demand : d. Use the method of catching exceptions , To handle the case that the user enters invalid data . """ zhong = float(input(" Please enter the purchase weight :")) jiage = float(input(" Please enter the price :")) try: float(zhong) float(jiage) except Exception: print(" The input data is wrong !") raise else: zongjia = zhong * jiage print(" You need to pay :{}".format(zongjia))