[phase I] 12. Python modules and packages

Keywords: Python

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:
characterintroduce
%YYear, e.g. 2020
%mMonth, 1 ~ 12
%dDays, 1 ~ 31
%HHours, 00 ~ 23
%IHours, 01 ~ 12
%MMinutes, 00 ~ 59
%SSeconds, 0 ~ 61 (leap years account for 2 seconds more)
%fmillisecond
%aWeek abbreviation, e.g. Wednesday Wed
%AWrite all weeks, such as Wednesday
%bMonth abbreviation, such as February, Feb
%BAll months are written, such as February and February
%cLocal date and time, e.g. Wed Feb 5 10:14:29 2021
%pDisplays morning and afternoon. For example, AM indicates morning and PM indicates afternoon
%jWhat day of the year
%UNumber 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 nameparameterintroduceExampleReturn value
getcwdnothingReturns the current pathos.getcwd()character string
listdirpathReturns all files or directories in the specified pathos.listdir('/etc/nginx')Returns a list
makedirspath,modeCreate multi-level directoryos.makedirs('/software/pathon')nothing
removedirspathDelete multi-level directoryos.removedirs('/software/python')nothing
renameold_name,new_nameRename a file or file nameos.rename('/software/python', '/software/py')nothing
rmdirpathOnly empty directories can be deletedos.rmdir('/software/python')nothing
  • os.path module:

The os.path module is mainly used to obtain the attributes of the file.

Function nameparameterintroduceExampleReturn value
existspathDoes the file or path existos.path.exists('/software')bool type
isdirpathIs it a pathos.path.isdir('/software')bool type
isabspathIs it an absolute pathos.path.isabs('python')bool type
isfilepathIs it a fileos.path.isfile('/software/python/test.py')bool type
joinpath1,path2Path string mergeos.path.join('/software', 'python')character string
splitpathCutting based on the last layer pathos.path.split('/software/python')tuple
  • sys module:

sys module mainly provides system specific parameters and functions.

Function nameparameterintroduceExampleReturn value
modules (properties)nothingModules loaded at python startupsys.moduleslist
path (property)nothingReturns the environment path of the current pythonsys.pathlist
exitargExit programsys.exit(0)nothing
getdefaultencodingnothingGet system codesys.getdefaultencoding()character string
platform (properties)nothingGet current system platformsys.platformcharacter string
vesion (properties)nothingGet python versionsys.versioncharacter string
argv (attribute)*argsGet the command line parameter list passed to python outside the programsys.argvlist

Posted by duk on Fri, 10 Sep 2021 18:00:46 -0700