Module is the code that encapsulates a particular function.
The modules are divided into three types:
Custom Modules
Third-party modules
Built-in Modules
1. Custom Modules
The custom module is the module of its own definition, how to import the custom module, as follows:
(1) The main program and the module program in the same directory: as the following program structure: '-- src |-- mod1.py '-- test1.py Import *;
(2) the directory where the main program is located is the parent (or grandparent) directory of the module's directory as follows: '-- src |-- mod1.py |-- mod2 | '-- mod2.py '-- test1.py If the module is imported into the program test1.py MOD2
from Import * or import mod2.mod2.
(3The main program is imported into the upper directory module or other directory (level) under the module such as the following program structure: '--src|--mod1.py|--mod2| `--mod2.py|--Sub| `--test2.py '--test1.py If the module mod1 and MOD2 are imported in the program test2.py. The method is called as follows:ImportOSImportSyspath= Os.path.dirname (Os.path.dirname (__file__) #获取test2 The root sub of the. Py, and then get the sub root directory srcsys.path.insert (0, path) #将src目录添加到环境变量ImportMod1ImportMod2.mod2
When the interpreter encounters an import statement, the module is imported if it is in the current search path.
A search path is a list of all directories that an interpreter will search first. If you need to import module support, you need to place the command at the top of the program
- A module will only be imported once
- The Python interpreter, in turn, looks for the modules introduced in the directory at the first level.
- The process of looking up a module is a bit like an environment variable, and you can actually determine the path of the search by defining the environment variable.
- The search path is determined by Python compilation or installation, and the installation of a new library should also be modified, and the search path is stored in the PATH variable in the SYS module
2. Third-party modules
How to install a third-party module, there are 2 ways to install, as follows:
The first type of installation:
The Python3 comes with a pip3,python2.7 that comes with a PIP, provided the PIP3 (scripts directory) is added to the environment variable.
PIP3 Install a module for installation xxx
PIP List view installed modules
Pip Uninstall XXX module uninstalled
Second installation method, manual installation:
First download the installation package, direct Baidu search for example, Python requests module
Unpacking the installation package
Execute Python setup.py install under the extracted directory
3. Built-in module random module
ImportRandomPrint(Random.randint (1, 20))#randomly generates an integer between 1-19, randomlyPrint(Random.choice ('abs123'))#Randomly takes an element, randomly iterating over an object: A string, a dictionary, a list, a tuplePrint(Random.sample ('Abcdfgrtw12', 3))#randomly take a few elements, 3 is the length, [' 2 ', ' A ', ' B '], and the result is a list typePrint(Random.uniform (1, 9))#Random floating-point number, random 1-9 floating-point number, can be specified range, 5.8791750348305625Print(Random.random ())#random 0-1 floating-point number, 0.9465901444615425Random.shuffle ([1, 2, 3, 4, 5, 6])#randomly disturb the list value, only the list
OS Module
ImportOSPrint(OS.GETCWD ())#get the working directory where the current py file is located: E:\python_workspace\base-code\day6
Os.chdir ('.. /') #更改当前的工作目录
print (OS.GETCWD ()) #更改后的目录: E:\python_workspace\base-code
Print (Os.mkdir (' test01 ')) #在当前工作目录创建文件夹
Print (Os.mkdir (' e:/python_workspace/base-code/test01 ')) #在其他目录下创建文件夹时, need to write absolute path
Print (Os.makedirs (R ' Test02\test2 ')) #创建多层目录 if the created parent directory (TEST02) does not exist, the creation succeedsPrint(Os.rmdir ('test01'))#Delete the empty folder under the current directory, if the folder has content, the deletion fails#Print (Os.removedirs (R ' Test02\test2 ')) #删除多层文件夹, delete fails if file is in the folderPrint(Os.remove ('ac.py'))#Delete file, throw OSError exception if incoming folder
Print(Os.rename ('a.py','ab.py'))#re-command, change a.py to ab.pyPrint(Os.listdir ('.'))#Print all the files in the current directory and return the results to listPrint(OS.SEP)#gets the path delimiter for the current system \Print(__file__)#prints the absolute path of the current filePrint(Os.path.abspath ('a.py'))#get the absolute path to the a.pyPrint(Os.path.abspath (__file__))#gets the absolute path of the current filePrint(Os.path.dirname (__file__))#gets the parent directory of the current file (that is, the top-level directory information)Print(Os.name)#gets the name of the current system, and win returns the NT
Os.system ('ipconfig')#Os.sysytem is used to execute system commands, run the ipconfig command, directly displayPrint(Os.path.exists ('test01'))#determine if a file or directory exists, and if present returns TruePrint(Os.path.isfile ('ab.py'))#determines whether a file, if it is a file, returns TruePrint(Os.path.isdir ('test01'))#determines if it is a directory and returns true if it is a directoryPrint(Os.path.isabs ("'))#returns True if path is an absolute pathPrint(Os.path.join ('e:', Os.sep,'AA','Abc.txt'))#stitching Path: E:\aa\abc.txtPrint(Os.path.join ('AC','Test','python'))#Ac\test\pythonPrint(Os.path.split ('Python_workspace/base-code/day6'))#separating directories and file names, returning results to tuples: (' Python_workspace/base-code ', ' Day6 ')
SYS module
ImportSysres= SYS.ARGV#command-line arguments in Terminal input command: Python rename.py b.txt 123 666, RES receives a list of results, the first element is the program itselfSys.exit (0)#exit program, normal exit N=0Sys.maxint#the largest int valueSys.path#returns the search path for the module, using the value of the PYTHONPATH environment variable when initializingSys.platform#returns the operating system platform nameSys.stdout.write ('Please :')#output A Word to the screenval = Sys.stdin.readline () [:-1]#gets the value entered
Time Module
Import TimePrint(Time.time ())#gets the timestamp of the current timePrint(Time.strftime ('%y%m%d%h%m%s'))#convert a time tuple to a string formatted for output, and you can debug the time format you wantPrint(Time.localtime ())#converts a timestamp to a time tuple and, if no timestamp is passed, the timestamp of the current time is obtained by defaultPrint(Time.localtime (1498056319))#convert timestamps to time tuples: Time.struct_time (tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=22, tm_min=45, tm_sec=19, tm_wday=2, tm_ yday=172, tm_isdst=0)Print(Time.mktime (Time.localtime ()))#convert a time tuple to a timestampTime.sleep (2)#Sleep TimePrint(Time.strptime ('20170618 144037','%y%m%d%h%m%s'))#convert formatted time to a time tuplePrint(Time.ctime (1498056319))#convert timestamp to wie format time: Wed June 22:45:19Print(Time.asctime ())#converts a time tuple to a formatted time, Wed June 21 22:52:37 2017, Standard Time
DateTime module
Import datetime Print (Datetime.datetime.now ()) # formats the current time output, similar to Time.strftime ('%y%m%d%h%m%s ') Print (Datetime.datetime.now () + Datetime.timedelta (2)) # 2 days after the time 2017-06-23 22:56:24.150894 Print (Datetime.datetime.now () + Datetime.timedelta ( -1)) # 1 days ago the time 2017-06-20 22:56:45.05809
Python Note 6: Common modules