The path to Python learning-modules

Source: Internet
Author: User
Tags local time python script timedelta

First, the module:

module, which implements a set of code for a function with a mound code.

Like functional programming and process-oriented programming, functional programming accomplishes a function, and other code is used to invoke it, providing reusability of code and coupling between the code. For a complex function, multiple functions may be required to complete (functions can be in different. py files), and the Code collection consisting of N. py files is called a module.

such as: OS is a system-related module; file is a module related to the operation of files

The modules are divided into three types:

    • Custom Modules
    • Built-in Modules
    • Open source Module

Second, the Import module:

Import Module  from Import xx  from Import xx as rename    from Import *   #  This method is not recommended for use. 
How to import modules

The import module actually tells the Python interpreter to explain the py file.

    • Import a py file, the interpreter interprets the py file
    • Import a package, the interpreter interprets the __init__.py file under the package

The base path of the import module path needs to be viewed using Sys.path, as follows:

ImportSYSPrint(Sys.path) above example Linux output: ["','/usr/lib/python2.7','/usr/lib/python2.7/plat-linux2','/USR/LIB/PYTHON2.7/LIB-TK','/usr/lib/python2.7/lib-old','/usr/lib/python2.7/lib-dynload','/usr/local/lib/python2.7/dist-packages','/usr/lib/python2.7/dist-packages','/usr/lib/pymodules/python2.7'] The above instance Windows output: ['E:\\project\\s12\\day5','E:\\PROJECT\\S12','e:\\project\\stu104381','C:\\users\\administrator\\appdata\\local\\programs\\python\\python35\\python35.zip','C:\\users\\administrator\\appdata\\local\\programs\\python\\python35\\dlls','C:\\users\\administrator\\appdata\\local\\programs\\python\\python35\\lib','c:\\users\\administrator\\appdata\\local\\programs\\python\\python35','c:\\users\\administrator\\appdata\\local\\programs\\python\\python35\\lib\\site-packages']

To add a module path:

Import SYS Import  = Os.path.abspath ('.. /') sys.path.append (Pre_path)
Add a module path

Note: Sys.path is a list as long as the path to be added append to the inside.

Three, Time and datetime modules:

Print(Time.clock ())#Return Processor TimeThe result of the above example output:7.07798237865507e-07Print(Time.process_time ())#Return Processor TimeThe result of the above example output:0.046800299999999996Print(Time.time ())#returns the current system timestampThe result of the above example output:1454318920.473497Print(Time.ctime ())#output Current system timeabove example output: Mon Feb1 17:30:02 2016Print(Time.ctime (Time.time ()-86640))#take yesterday's time. above example output: Sun Jan31 17:26:54 2016Print(Time.gmtime (Time.time ()))#struct_time format to take the current timeThe above example output: Time.struct_time (tm_year=2016, tm_mon=2, Tm_mday=1, tm_hour=9, tm_min=33, tm_sec=49, tm_wday=0, tm_yday=32, tm_isdst=0)Print(Time.localtime (Time.time ()))#in struct_time format, but returns local timeThe above example output: Time.struct_time (tm_year=2016, tm_mon=2, Tm_mday=1, tm_hour=17, tm_min=37, tm_sec=56, tm_wday=0, tm_yday=32, tm_isdst=0) Note: The difference between gmtime and localtime is that the gmtime back is Greenwich Mean time, and LocalTime returns to Beijing. Print(Time.mktime (Time.localtime ()))#reverse the Struct_time format to a timestamp format, as opposed to the Time.localtime () functionThe result of the above example output:1454319614.0Time.sleep (4)#Sleep 4 secondsPrint(Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()))#converts the Struct_time format to the specified string formatThe result of the above example output:2016-02-01 17:43:34Print(Time.strptime ("2016-02-01","%y-%m-%d") )#convert string format to struct_time formatThe above example output: Time.struct_time (tm_year=2016, tm_mon=2, Tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=32, Tm_isdst=-1)
Time Module
Print(Datetime.date.today ())#output Format%y-%m-%d format outputThe result of the above example output:2016-02-01Print(Datetime.date.fromtimestamp (Time.time ()))#2016-01-16 turn timestamps into date formatsThe result of the above example output:2016-02-01Print(Datetime.datetime.now ())#output date with millisecond levelThe result of the above example output:2016-02-01 17:51:46.091749Current_time=Datetime.datetime.now ()Print(Current_time.timetuple ())#return to Struct_time formatThe above example output: Time.struct_time (tm_year=2016, tm_mon=2, Tm_mday=1, tm_hour=17, tm_min=54, tm_sec=11, tm_wday=0, tm_yday=32, Tm_isdst=-1) Current_time=Datetime.datetime.now ()Print(Current_time.replace (2013,6,12))#returns the current time, but the specified value is replacedThe result of the above example output:2013-06-12 17:56:01.377351Print(Datetime.datetime.strptime ("21/11/06 16:30","%d/%m/%y%h:%m"))#Convert a string into a date formatThe result of the above example output:2006-11-21 16:30:00Print(Datetime.datetime.now () + Datetime.timedelta (days=10))#10 days longer than now .The result of the above example output:2016-02-11 17:59:18.593631Print(Datetime.datetime.now () + Datetime.timedelta (days=-10))#minus 10 days now .The result of the above example output:2016-01-22 18:00:29.296675Print(Datetime.datetime.now () + Datetime.timedelta (hours=-10))#minus 10 hours now .The result of the above example output:2016-02-01 08:00:58.682356Print(Datetime.datetime.now () + Datetime.timedelta (seconds=120))#+120s than now .The result of the above example output:2016-02-01 18:03:45.592039
datetime Module

Iv. Random Module

The random module is used to generate the following numbers:

Import Random Print (Random.random ())     # random values.  result of the above instance output:0.7037924498861795Print(Random.randint (1, 2))  #  A value is randomly output between 1 and 2. The result of the above example output:2print# randomly outputs a value between 1 and 10.  result of the above instance output:9
Random module:

To generate a verification code using the random module:

Import" for" in range (4):    = Random.randrange (0,4)     if current! = I        := Chr (Random.randint (65,90)    )else:         = random.randint (0,9)    + = Str (temp)print(checkcode) Result of the above example output: e59j
Verification Code instance:

Five, OS module:

An OS module is an interface to a system operation:

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work os.chdir ("dirname") To change the current script working directory, equivalent to the shell under Cdos.curdir return to the current directory: ('.') Os.pardir Gets the parent directory string name of the current directory: ('..') Os.makedirs ('dirname1/dirname2') to generate a multi-level recursive directory Os.removedirs ('dirname1'If the directory is empty, it is deleted and recursively to the previous level of the directory, if it is also empty, then delete, and so on Os.mkdir ('dirname') to generate a single-level directory, equivalent to the shell mkdir Dirnameos.rmdir ('dirname'Delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir Dirnameos.listdir ('dirname'lists all files and subdirectories under the specified directory, including hidden files, and prints a list of os.remove () deletes a file Os.rename ("oldname","newname") Rename File/Catalog Os.stat ('Path/filename') Get File/directory information OS.SEP output operating system-specific path delimiter, win under"\\", under Linux for"/"os.linesep Output The line terminator used by the current platform, win under"\t\n", under Linux for"\ n"the OS.PATHSEP output string that is used to split the file path Os.name the output strings indicates the current usage platform. Win-'NT'; Linux->'POSIX'Os.system ("Bash Command"run the shell command to directly display the Os.environ get system environment variable Os.path.abspath (PATH) return path normalized absolute path Os.path.split (path) Split path into directory and file name two tuples return Os.path.dirname (path) to the directory where path is returned. In fact, the first element of Os.path.split (path) os.path.basename returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path), os.path.exists (path), returns True if path exists, or if path does not exist, returns Falseos.path.isabs if path is an absolute path, Returns Trueos.path.isfile (path) If path is an existing file and returns True. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists.  Otherwise return Falseos.path.join (path1[, path2[, ...])  When multiple paths are combined, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the last modified time of the file or directory to which path is pointing
OS module:

Six, sys module

SYS.ARGV           command line argument list, the first element is the program itself path Sys.exit (n)        exits the program, exit normally (0) sys.version        Gets the version information of the Python interpreter Sys.maxint         the largest int value Sys.path           returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing Sys.platform       Returns the operating system platform name
SYS module:
Import Sys,time  for  in range:    sys.stdout.write ("#")    Sys.stdout.flush ()    time.sleep (0.3)
example of a progress bar:

VII. module JSON and pickle for serialization

Json: The serialized data can be passed before any language.

Picke: The serialized data can only be passed before Python, but Picke can serialize most of the data types, such as functions.

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

The path to Python learning-modules

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.