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

Python notes 15- packages and modules

編輯:Python

One 、 Packages and modules

1. package

package 【package】 It's a kind of Management Python The form of the module namespace , use " Point module name "

It's like using modules , You don't have to worry about the same global variables between different modules , In the form of point module name, there is no need to worry about the duplicate names of modules between different libraries

package It's essentially a folder 【 Catalog 】, But the special thing is : There is a file under this folder __init__.py, Represents initialization , But the early stage is empty , Later in the project development , The configuration information of some items will be written in it
Be careful : actually , One py File is a module , A module name includes package name and file name
Such as :import aaa.file ,aaa Indicates the package name or directory name .file File name , Both make up a module name
"""
Be careful :
1. Packages exist to manage modules , In essence, it is to manage py file 【 One py File is a module 】
2. If you want to access variables in another module in one file , Or function or class , No direct access , You need to import the module first , And then visit again
3. If you need to import a customized module , You need to pay attention to the path problem , Using relative paths , Packages and folders are used the same
a. By default , Start from the root directory of the current project , No matter how complex the hierarchy of the directory is , Pay attention to the way of writing
b. You can mark the specified package or directory as the root directory , When writing the path of the module , You can start writing from the root directory of the tag
Way of marking : Select the package or directory to be marked ---》 Right click ----》Mark Directory as---->Source Root
4.import xxx,xxx It can contain the package name , Directory name and py file name
"""
# 1. System module
import random # Load is py file
import math # Load is py file
print(math.pi)
print(math.sqrt(9))
n1 = random.choice(range(10))
print(n1)
# 2. Import the custom module in the custom package
import aaa.module
import bbb.module
print(aaa.module.num)
print(bbb.module.num)
# It starts from the project root directory by default
# import ccc.c1.c2.text
# print(ccc.c1.c2.text.num1)
# print(ccc.c1.c2.text.num2)
# print(ccc.c1.c2.text.num3)
# Mark c1 Is the root directory of the resource
# import c2.text
# print(c2.text.num1)
# print(c2.text.num2)
# print(c2.text.num3)
# Mark c2 Is the root directory of the resource
import text
print(text.num1)
print(text.num2)
print(text.num3)

2. Custom module

 At present, there are few codes , There are no shortcomings in writing in one document , But as the amount of code increases , The code becomes more and more difficult to maintain .
To solve problems that are difficult to maintain , We group many functions with similar functions , Put them in different files . Thus, each file contains relatively less content , And the general function of each file can be reflected by the file name . This is how many programming languages organize code structures .

Be careful : Actually, one. .py File is a module

【 Interview questions 】 advantage :

  • Improve code maintainability
  • Improved code reuse , When a module is written , Can be referenced in multiple places
  • Reference other modules
  • Avoid naming conflicts between function names and variable names

2.1 Import method 1

# 1.import xxxx: Import a module , Import all the contents allowed to be loaded in the module
# Mode one
# import aaa.module
# import bbb.module
# Mode two
import aaa.module,bbb.module
# import random,math
print(aaa.module.num)
print(bbb.module.num)
aaa.module.func()
bbb.module.func()
# 2.import xxxx as xxxx: Import a module , Import all the contents allowed to be loaded in the module
# as Indicates that the module is aliased , Generally, the path relationship of modules is complex
import ccc.c1.c2.text as c
print(c.num1)
print(c.num2)
print(c.num3)
"""
import xxx
advantage :
If there are variables with the same name in different modules , A function or class , It does not affect each other when used
shortcoming :
Every time you access a variable , Function or class , You need to declare the module name , The code is tedious
"""
# Conclusion : Use a module , You only need to import once , It doesn't make sense to import more than once ,
# In order to save resources and improve work efficiency , The specified module will not be loaded repeatedly

2.2 Import mode 2

# 1.from Module name import Variable , function , class
from aaa.module import num,func,func1
from bbb.module import num,func
from ccc.c1.c2.text import num1
print(num)
func()
func1()
print(num1)
# 2.from Module name import *, Indicates that all are imported
# from aaa.module import *
# from ccc.c1.c2.text import *
# print(num)
# func()
# func1()
# print(num1)
# print(num2)
# print(num3)
"""
from xxx import xxxx
advantage :
Access variables , Function or class , There is no need to declare the module path
You can selectively import the variables you need to use , Function or , Can save memory space
shortcoming :
If a variable with the same name appears in different modules , A function or class , Then the latter will overwrite the former
If a module contains a large number of variables , A function or class , If you need to use it all , Importing in sequence can be very cumbersome , You can use from Module name import * Simplify
"""

2.3dir() and name

import random
import aaa.module
# 1.dir(): List all contents contained in a module
# print(dir(random))
# print(dir(aaa.module))
# List all the contents contained in an object
# print(dir('abc'))
# print(dir([34,6]))
#2.__name__
"""
characteristic :
If run What is important is the module itself ,__name__ The value of is __main__
If run Other documents , Modules are imported ,__name__ The value of is the module name
effect :
A Modules are imported into other files for use , If some of the code doesn't want to be executed , Then you can ' shielding ' To if __name__ == "__main__"
purpose :
If you encapsulate a function in a module , You can test calls in the current module , It can also be imported and used in other files ,
At this point, you can write the code of the test call to if __name__ == "__main__"
"""

3. System module

3.1time modular

Python The program can handle dates and times in many ways , Converting date formats is a common feature .
Python Provides a time and calendar Module can be used to format date and time .
The time interval is a floating-point decimal in seconds .
Every time stamp comes from 1970 year 1 month 1 Midnight ( Epoch ) How long does it take to express .
Python Of time There are many functions under the module that can convert common date formats

1> A term is used to explain

UTC, Greenwich astronomical time , World standard time , In China for UTC+8

DST: Daylight saving time , Display format of time

2> The representation of time 【 master 】

a. Time stamp

 An integer or floating-point representation is a time interval in seconds , The base value of this time is 1970.1.1 Starting from zero of

b. Time tuple format

 use Python Data structure representation of , This tuple has 9 An integer content , They have different meanings

c. Formatted time string

from time import *
# 1.time(): Get the timestamp of the current time ******
t1 = time()
print(t1)
# 2.gmtime(): Get current UTC, In tuple form
t2 = gmtime()
print(t2)
# 3.localtime(): Get local time ,, In tuple form ******
t3 = localtime()
print(t3)
# 4.mktime(): Convert the tuple form of time to timestamp
t4 = mktime(t3)
print(t4)
# 5.ctime(): A string that converts a timestamp to time , The default format
t5 = ctime(t1)
print(t5) # Sat Aug 14 21:50:39 2021
# 6. Convert the time tuple form to a string of time , The default format
t6 = asctime(t3)
print(t6) # Sat Aug 14 21:52:17 2021
# 7.strftime(): Convert the tuple form of time to the string of time , You can customize the format *****
# %Y:year %m:month %d:day %H:hour %M:minutes %S:seconds
t7 = strftime("%Y.%m.%d",t3)
print(t7) # 2021.08.14
t7 = strftime("%Y.%m.%d %H:%M:%S",t3)
print(t7) # 2021.08.14 21:55:07
t7 = strftime("%Y/%m/%d %H:%M:%S",t3)
print(t7) # 2021/08/14 21:55:23
# 8.strptime(): Convert the string form of time to the tuple form of time , It can also be understood as parsing a time string ******
# Be careful : When parsing the time string , Be sure to pay attention to the exact match between the time string and the time format
# t8 = strptime("2021/08/14 21:55:23","%Y.%m.%d")
# print(t8) # ValueError: time data '2021/08/14 21:55:23' does not match format '%Y.%m.%d'
t8 = strptime("2021/08/14 21:55:23","%Y/%m/%d %H:%M:%S")
print(t8)
# 9.sleep(): Sleep , Put the program into a blocking state , After the specified time , Will automatically unblock , The program will continue to go down *****
# Use scenarios : It is widely used in processes and threads
print("start")
sleep(5)
print("over")

3.2datetime modular

# datetime The module is in time On the basis of the module, the secondary packaging is carried out
import datetime
"""
date: date , Including mm / DD / yyyy
time: Time , Including hours, minutes and seconds
datetime: Date and time , Including month, day, hour, minute, second
tzinfo: The time zone
"""
# 1. Get the current time ****
d1 = datetime.datetime.now()
print(d1) # 2021-08-03 11:46:57.798894
print(type(d1))
# 2. Convert time to string 【 Formatting of time string 】
"""
Placeholder for time
%Y: year
%m: month
%d: Japan
%H: when
%M: branch
%S: second
%d: Japan %D: month / Japan / year
%Y:2021 %y:21
%H: when %h: English of month
"""
d2 = datetime.datetime.now()
time_str1 = d2.strftime("%Y.%m.%d %H:%M:%S")
print(time_str1)
print(type(time_str1))
# 3. Convert format string to time format
# Be careful : When parsing the time string , Be sure to pay attention to format matching
d3 = datetime.datetime.strptime(time_str1,"%Y.%m.%d %H:%M:%S")
print(d3)
print(type(d3))
# 4. Two time objects can be subtracted *****
date1 = datetime.datetime(2020,10,1,14,15,30,100)
date2 = datetime.datetime(2020,10,3,13,30,31,100)
d4 = date2 - date1
print(d4)
print(d4.days) # property attribute
print(d4.seconds)

3.3calendar modular

import calendar
# 1. Determine if it's a leap year *****
print(calendar.isleap(2020))
# 2. Get the perpetual calendar of the specified year and month
print(calendar.month(2020,10))
# 3. Get the perpetual calendar of the specified year
print(calendar.calendar(2020))
# 4. Gets the week of the specified date , The value range is :0~6
print(calendar.weekday(2021,8,8))
# 5. Get the number of leap years between the specified years
print(calendar.leapdays(2000,2021))
print(dir(calendar))

3.4os modular 【 important 】

os The module contains common operating system functions , There are plenty of ways to deal with files and directories

Basic use

# os The module contains common operating system functions , It provides very rich functions for processing files or folders
import os
# One 、os Function under module
# 1.listdir(path): List all contents under the specified path , Contains files and folders , ********
# Return a list , The element is the name of the file or folder
path = r"/Users/yangyang/Desktop/coding14" # Absolute path
r1 = os.listdir(path)
print(r1)
# 2.mkdir(path): Create a directory ******
# os.mkdir(r"aaa") # Relative paths
# open(): Create a file
# f1 = open(r"a1.txt","w",encoding="utf-8")
# 3.rmdir(path): Delete a directory
# os.rmdir(r"aaa")
# 4.remove(path): Delete a file
# os.remove(r"a1.txt")
# 5.rename(old,new): Rename the specified file or folder
# os.rename(r"aaa","bbb")
# os.rename(r"a1.txt",'file.txt')
# Two 、os.path Function under module *********
# 1.join( Parent path , Subpath ): Splicing path
path = r"/Users/yangyang/Desktop/coding14"
subpath = r"Day2Code"
# a.+, It is not recommended to use , reason :python It's cross platform , however , If the + The way to splice paths , Different operating systems have different splicing methods
# new_path1 = path + "/" + subpath # stay windows in ,new_path1 = path + "\\" + subpath
# print(new_path1)
# b.join()
new_path2 = os.path.join(path,subpath)
print(new_path2)
# 2.split(path): Split the path , The result is a tuple , Format :( Parent path , Subpath )
r1 = os.path.split(path)
print(r1)
path1 = r"/Users/yangyang/Desktop/coding14/Day2Code/5. Input print.py"
r1 = os.path.split(path1)
print(r1)
# 3.splitext(path): Split the path , The result is a tuple , Format :( Parent path , Extension )
# If path It's a folder , The result is ( Parent path ,""), If path It's a document , The result is ( Parent path ,". Extension ")
print(os.path.splitext(path))
print(os.path.splitext(path1))
# 4.isfile(path): Determine whether the specified path is a file
print(os.path.isfile(path1))
print(os.path.isfile(path))
# 5.isdir(path): Determine whether the specified path is a folder
print(os.path.isdir(path1))
print(os.path.isdir(path))
# 6.exists(path): Judge path Whether there is
print(os.path.exists(path))
# 7.getsize(path): Get the byte size of a file , It is often used in file reading and writing
print(os.path.getsize(path1))

application

# os:operation system, operating system
import os
# 1. Important functions
# a.listdir(path): List all contents under the specified path , Package live files and folders
path = r"/Users/yangyang/Desktop/Coding16"
r1 = os.listdir(path)
print(r1)
# b.join(path1,path2): Splicing path , It can automatically identify the system , Use the corresponding splicing symbol
# Mac:/ windows:\
# Manual splicing , Not recommended
# path1 = path + '/' + 'Day9'
# print(path1)
path1 = os.path.join(path,'Day9')
print(path1)
# c.isfile(path)/isdir(path): Determine whether a specified path is a file / Folder
path1 = '/Users/yangyang/Desktop/Coding16/Day2/notes/Day2 note - Data types and variables & Input and output .md'
print(os.path.isfile(path))
print(os.path.isfile(path1))
print(os.path.isdir(path))
print(os.path.isdir(path1))
# 2. application
# demand : Encapsulate a function , Get all the... Under a specified path and all sub paths py file
def getfile(path):
# Judge path Whether there is
if not os.path.exists(path):
print(" path does not exist , Can't operate ")
return
# Judge path Is it a document
if os.path.isfile(path):
print(" The path is a file , Can't operate ")
return
# Paths exist , The path is a folder
# obtain path All the content
subpath_list = os.listdir(path)
# print(subpath_list)
# Traverse the directory
for filename in subpath_list:
# Splice subpath
subpath = os.path.join(path,filename)
# print(subpath)
# Determine whether the sub path is a file and whether it is py file
if os.path.isfile(subpath): # file
if subpath.endswith(".py"):
print(f"【{subpath}】 It's a py file ")
else: # Folder
# If it's a folder , The above operation will be repeated : obtain --》 Traverse ---》 Judge
getfile(subpath)
if __name__ == '__main__':
path = r"/Users/yangyang/Desktop/Coding16"
getfile(path)

3.5string modular

# string Modules are modules about strings
import string
# 1. Get all decimal characters ******
print(string.digits)
# 2. Get all uppercase letters
print(string.ascii_uppercase)
# 3. Get all lowercase letters
print(string.ascii_lowercase)
# 4. Get all the letters *******
print(string.ascii_letters)
# 5. Get all octal or hexadecimal
print(string.octdigits)
print(string.hexdigits)
# 6. Get all punctuation marks
print(string.punctuation)
# 7. Get all whitespace characters : Space ,tab, enter , Line break, etc
print(string.whitespace)
# 8. Get all printable characters
print(string.printable)

4. Third-party module

How to install third-party modules :

 Mode one :file--->settings---->Project--->Project Interpreter ---->+
Mode two : stay cmd in , perform pip install xxxx -i Mirror source
Mode three : install Anaconda, amount to Python, It's just that... Has been installed 180+ The above third-party modules

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