python modules and packages
- python packages and modules:
python packages are folders, and packages can also have sub packages, that is, sub folders.
python modules are. py files that define various functional interfaces. Encapsulate complex functions into modules (also known as libraries) and hide the details of function implementation. Programmers who use this module (Library) do not need to know the details of implementation.
In the application fields of python, such as web development, artificial intelligence, web crawler, data analysis and so on, there are a large number of modules. Using these modules, you can easily develop applications.
Hierarchical relationship: package → module → function
- ID card of package:
__ init__.py is a file that must exist in every python package.
Therefore, when creating a package, you must create one under the package__ init__.py file__ init__. The contents of the PY file can be empty, but the file must exist.
When creating a package, you should pay attention to: 1. There should be a theme, clear functions and easy to use; 2. Clear hierarchy and clear calling.
- Import of package:
If you want to use a package or module, you should first import the package or module into the current. py file.
In python, the keyword for importing a package or module is import.
Usage:
import package
The parameter package indicates the name of the imported package.
- Module import:
Module import is somewhat similar to package import. From... Import... You can import the specified module from a package.
Usage:
from package import module
The parameter package represents the name of the package to which the imported module belongs, and module represents the name of the imported module.
If there are sub packages under a package, the package names are connected through. Through from package.child_package import module to import modules in sub packages.
- Import module setting alias:
Sometimes the module names imported from different packages may be the same. In this case, you can set an alias for the module during import. From... Import... As... You can import the specified module from a package and set the alias.
Usage:
from package import module as module_name
The parameter package represents the name of the package to which the imported module belongs, module represents the name of the imported module, and module_name indicates the alias set.
- Third party packages:
The functions written by other programmers are encapsulated into packages (modules) and published online, which is the third-party package. Using third-party packages can effectively improve development efficiency.
You can use python's third-party package management tools PIP and easy_install obtains third-party packages, of which pip is the most used.
Install the specified package through the command pip install package, for example, install ipython: pip install ipython. You can also search for python third-party packages through github.com.
- datetime package:
The datetime package can obtain the current date, time and time interval, convert the time object into a time string, and convert the string into a time type.
The datetime function of the datetime module can be used to obtain the current date and time. Usage:
from datetime import datetime or import datetime
The timedelta function of the datetime module can be used to obtain the time interval. Usage:
from datetime import datetime from datetime import timedelta
The timedelta function has parameters such as days, hours, minutes, seconds, microseconds, milliseconds and week.
Example:
# coding:utf-8 from datetime import datetime from datetime import timedelta print(datetime.now()) yestoday = datetime.now() - timedelta(days=1) print(yestoday) tomorrow = datetime.now() + timedelta(days=1) print(tomorrow)
result:
2021-07-09 16:13:15.579308 2021-07-08 16:13:15.579308 2021-07-10 16:13:15.579308
The timestamp function of the datetime module can be used to convert a time object into a timestamp. Usage:
from datetime import datetime now = datetime.now() datetime.timestamp(now)
The parameter now represents the datetime time object and returns a timestamp.
Example:
# coding:utf-8 from datetime import datetime now = datetime.now() now_timestamp = datetime.timestamp(now) print(now_timestamp)
result:
1625818747.073041
The fromtimestamp function of the datetime module can be used to convert a timestamp into a time object. Usage:
from datetime import datetime datetime.fromtimestamp(timestamp)
The parameter timestamp represents the timestamp and returns a datetime time object.
Example:
# coding:utf-8 from datetime import datetime time_stamp = 1625818747.073041 now = datetime.fromtimestamp(time_stamp) print(now)
result:
2021-07-09 16:19:07.073041
The strftime function of the datetime module can be used to convert a time object into a string. Usage:
from datetime import datetime now = datetime.now() date_str = now.strftime(format)
The parameter format represents the time object matching rule.
# coding:utf-8 from datetime import datetime date = datetime.now() print(type(date)) date_str = date.strftime('%Y-%m-%d %H:%M:%S') print(date_str) print(type(date_str))
result:
<class 'datetime.datetime'> 2021-07-09 16:22:23 <class 'str'>
The strptime function of the datetime module can be used to convert a time string into a time object. Usage:
from datetime import datetime datetime.strptime(tt, format)
The parameter tt represents the string conforming to the time format, and format represents the time string matching rule.
# coding:utf-8 from datetime import datetime date_str = '2021-07-09 16:22:23' date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') print(date_obj) print(type(date_obj))
result:
2021-07-09 16:22:23 <class 'datetime.datetime'>
- Time format characters:
character | introduce |
---|---|
%Y | Year, e.g. 2020 |
%m | Month, 1 ~ 12 |
%d | Days, 1 ~ 31 |
%H | Hours, 00 ~ 23 |
%I | Hours, 01 ~ 12 |
%M | Minutes, 00 ~ 59 |
%S | Seconds, 0 ~ 61 (leap years account for 2 seconds more) |
%f | millisecond |
%a | Week abbreviation, e.g. Wednesday Wed |
%A | Write all weeks, such as Wednesday |
%b | Month abbreviation, such as February, Feb |
%B | All months are written, such as February and February |
%c | Local date and time, e.g. Wed Feb 5 10:14:29 2021 |
%p | Displays morning and afternoon. For example, AM indicates morning and PM indicates afternoon |
%j | What day of the year |
%U | Number of weeks in a year |
- time module:
The time function of the time module can be used to generate a timestamp. Usage:
import time time.time()
The localtime function of the time module can be used to obtain the local time. Usage:
import time time.localtime(timestamp)
The parameter timestamp indicates the timestamp, which can be omitted.
Example:
# coding:utf-8 import time now = time.time() print(now) now_localtime = time.localtime() print(now_localtime) print(time.localtime(now))
result:
1625824032.844112 time.struct_time(tm_year=2021, tm_mon=7, tm_mday=9, tm_hour=17, tm_min=47, tm_sec=12, tm_wday=4, tm_yday=190, tm_isdst=0) time.struct_time(tm_year=2021, tm_mon=7, tm_mday=9, tm_hour=17, tm_min=47, tm_sec=12, tm_wday=4, tm_yday=190, tm_isdst=0)
The sleep function of the time module can be used to pause the program for a period of time. Usage:
import time time.sleep(second)
The parameter second indicates the number of seconds you want the program to be suspended. Usage:
Example:
# coding:utf-8 import time now_localtime = time.localtime() print(now_localtime) time.sleep(5) now_localtime = time.localtime() print(now_localtime)
result:
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=9, tm_hour=17, tm_min=56, tm_sec=13, tm_wday=4, tm_yday=190, tm_isdst=0) time.struct_time(tm_year=2021, tm_mon=7, tm_mday=9, tm_hour=17, tm_min=56, tm_sec=18, tm_wday=4, tm_yday=190, tm_isdst=0)
The strftime function of the time module can be used to convert a time object into a string. Usage:
import time time.strftime(format, t)
The parameter format represents the time object matching rule, and t represents the time type corresponding to time.localtime.
Example:
# coding:utf-8 import time time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) print(time_str) print(type(time_str))
result:
2021-07-09 18:01:01 <class 'str'>
The strptime function of the time module can be used to convert a time string into a time object. Usage:
import time time.strptime(t, format)
The parameter t represents the string conforming to the time format, and the format represents the time string matching rule.
Example:
# coding:utf-8 import time time_str = '2021-07-09 18:01:01' time_obj = time.strptime(time_str, '%Y-%m-%d %H:%M:%S') print(time_obj) print(type(time_obj))
result:
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=9, tm_hour=18, tm_min=1, tm_sec=1, tm_wday=4, tm_yday=190, tm_isdst=-1) <class 'time.struct_time'>
- os module:
os module can easily use the functions related to the operating system. Import the os module through import os.
Function name | parameter | introduce | Example | Return value |
---|---|---|---|---|
getcwd | nothing | Returns the current path | os.getcwd() | character string |
listdir | path | Returns all files or directories in the specified path | os.listdir('/etc/nginx') | Returns a list |
makedirs | path,mode | Create multi-level directory | os.makedirs('/software/pathon') | nothing |
removedirs | path | Delete multi-level directory | os.removedirs('/software/python') | nothing |
rename | old_name,new_name | Rename a file or file name | os.rename('/software/python', '/software/py') | nothing |
rmdir | path | Only empty directories can be deleted | os.rmdir('/software/python') | nothing |
- os.path module:
The os.path module is mainly used to obtain the attributes of the file.
Function name | parameter | introduce | Example | Return value |
---|---|---|---|---|
exists | path | Does the file or path exist | os.path.exists('/software') | bool type |
isdir | path | Is it a path | os.path.isdir('/software') | bool type |
isabs | path | Is it an absolute path | os.path.isabs('python') | bool type |
isfile | path | Is it a file | os.path.isfile('/software/python/test.py') | bool type |
join | path1,path2 | Path string merge | os.path.join('/software', 'python') | character string |
split | path | Cutting based on the last layer path | os.path.split('/software/python') | tuple |
- sys module:
sys module mainly provides system specific parameters and functions.
Function name | parameter | introduce | Example | Return value |
---|---|---|---|---|
modules (properties) | nothing | Modules loaded at python startup | sys.modules | list |
path (property) | nothing | Returns the environment path of the current python | sys.path | list |
exit | arg | Exit program | sys.exit(0) | nothing |
getdefaultencoding | nothing | Get system code | sys.getdefaultencoding() | character string |
platform (properties) | nothing | Get current system platform | sys.platform | character string |
vesion (properties) | nothing | Get python version | sys.version | character string |
argv (attribute) | *args | Get the command line parameter list passed to python outside the program | sys.argv | list |