Python Basics Module Part1

Source: Internet
Author: User

Module:

A module is essentially a Python program.

All that is said to be an object must be done by the object. method to implement some operations.

Module Type:

Built-in Modules

Third-party modules

Custom Modules

Import in the order of finding modules: built-in Modules----> third-party modules----> custom modules.

The Later Learning Network programming (socket) and threading process (threading processing) is actually learning these modules.

Time

Time is also a class in Python.

There are three types of time:

Timestamp: The timestamp represents the offset that is calculated in seconds, starting January 1, 1970 00:00:00. The timestamp viewed with Time.time () is a floating-point data

Structured time: The form of a tuple, a total of nine elements

String time: A convenient format for people to read. For example: ' 2017-06-21 19:31:18 '

Example:
Import Timeprint (Time.time ()) print (Time.localtime ()) Print (Time.strftime ("%y-%m-%d%x")) Execution Result: D:\Python\ Python36-32\python.exe e:/python/day-12/time module. Py1498045508.7362208time.struct_time (tm_year=2017, tm_mon=6, tm_ Mday=21, tm_hour=19, tm_min=45, Tm_sec=8, tm_wday=2, tm_yday=172, tm_isdst=0) 2017-06-21 19:45:08process finished with Exit Code 0

Three types of conversions:

Import Timeprint (Time.localtime (Time.time ()))    #转换时间戳为结构化时间print (Time.mktime (Time.localtime ()))   #转换结构化时间为时间戳print (time.strftime ('%y-%m-%d ', Time.localtime (Time.time ())))  #转换结构化时间为 string Time print ( Time.strptime (' 2017-06-22 ', '%y-%m-%d '))   #转换字符串时间为结构化时间执行结果: D:\Python\Python36-32\python.exe e:/python/ Day-12/time module. Pytime.struct_time (tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=19, tm_min=50, tm_sec=45, tm_wday=2, tm_ yday=172, tm_isdst=0) 1498045845.02017-06-21time.struct_time (tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=0, tm_min=0 , Tm_sec=0, Tm_wday=3, tm_yday=173, Tm_isdst=-1) Process finished with exit code 0

There is also a conversion of a fixed string structure:

Import Timeprint (Time.asctime (Time.localtime (3212334241)))    #结构化时间转换为固定格式字符串时间print (Time.ctime (3213213321))   #时间戳时间转换为固定格式字符串时间执行结果: D:\Python\Python36-32\python.exe e:/python/day-12/time module. Pysun Oct 03:04:01 2071Wed Oct 07:15:21 2071Process finished with exit code 0

Other methods:

Import Timestart = Time.time () time.sleep (5)     #暂停指定的时间后继续运行, unit of seconds stop = Time.time () print (' Sleep%s seconds '% (Stop-start)) Execution Result: D:\Python\Python36-32\python.exe e:/python/day-12/time module. Py slept for 5.00053095817566 seconds. Process finished with exit code 0

Random

Randomly generated modules.

>>> import random>>> random.random ()      # is greater than 0 and less than 1 decimal 0.7664338663654585>>> Random.randint (1,5)  # Integer greater than or equal to 1 and less than or equal to 5 >>> random.randrange (1,3) # greater than or equal to 1 and less than 3 integers >>> Random.choice ([1, '% ', [4,5]])  # #1或者23或者 [4,5]>>> random.sample ([1, ' 23°c ', [4,5]],2] # #列表元素任意2个组合 [[4, 5], ']>>> random.uniform (1,3) #大于1小于3的小数1 .6270147180533838>>> item=[1,3,5,7,9]>>> Random.shuffle (item) # Scrambled Order >>> item[5, 1, 3, 7, 9]>>> random.shuffle (item) >>> item[5, 9, 7, 1, 3]

A simple random captcha generator:

Import Randomdef Valdate_code ():    ret = ' for me ' in    range (5):        num = random.randint (0,9)        a1 = Chr (Random.ra Ndint (97,122))        a2 = Chr (Random.randint (65,90))        s = random.choice ([str (num), A1,A2])        ret = Ret+s    Return Retprint (Valdate_code ())

Hashlib:

Hashlib provides a common digest algorithm, such as MD5,SHA1.

Abstract algorithm, also known as hashing algorithm, hashing algorithm. Converts any length of data into a fixed-length data string through a function.

Abstract the algorithm is one-way irreversible.

Application: File consistency check, login

Example: Calculating the MD5 value of a string
Import Hashlib MD5 = HASHLIB.MD5 () #可以在这里的括号内进行 "Add salt" Note: Salt processing means adding a string to the original content, increasing the complexity of the checksum md5.update (' How To Use MD5 in Python hashlib? ') #update接收信息可以重叠接收print md5.hexdigest () #显示摘要信息执行结果: d26a53750bc40b38b65a520292f69306

Os

Operating system modules.

Some interfaces provided by the operating system, Python to invoke.

OS.GETCWD () Gets the current working directory, that is, the directory path of the current Python script work os.chdir ("DirName") changes the current script working directory, equivalent to the shell Cdos.curdir return the current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') can generate a multi-level recursive directory Os.removedirs (' dirname1 ') if the directory is empty, then deleted, and recursively to the previous level of the directory, if 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 os.remove () Delete a file Os.rename ("Oldname", "newname") Rename File/directory Os.stat (' Path/filename ') Get File/directory information OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/" OS.LINESEP output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep output is used to split the file path of the string win under;, Linux: The Os.name output string indicates the current use of the platform. Win-> ' NT ';  Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays the Os.environ get system environment variable Os.path.abspath (PATH) Return path normalized absolute path Os.path.split (path) splits 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) If path exists, returns true if path does not exist, returns Falseos.path.isabs (path) If path is an absolute path, return Trueos.path.isfile (PATH) Returns true if path is a file that exists. 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 size of the file or directory to which path was last modified Os.path.getsize (path) returned path

Python-based module part1

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.