Python common modules

Source: Internet
Author: User

Module: is essentially a. py file

Modules are divided into three parts: built-in modules, third-party modules, custom modules

One, Time module

1. Time representation

In Python, there are typically three ways to represent time:

(1) timestamp (timestamp): The timestamp represents the Folat type, which is measured in seconds from 00:00:00 January 1, 1970.

(2) formatted time string (format string): ' 2017-06-21

(3) Structured time: A total of 9 elements total nine elements: (year, month, day, hour, minute, second, week of the year, Day of the year, etc.)

2. Conversion of Time forms

Import Time#time.time () #仅仅显示当前时间的时间戳#time.localtime () #结构化时间对象 convert timestamps to structured time#time.gmtime () #世界标准时间 (UTC time)#Time.mktime (Time.localtime ()) #将结构化时间转换成时间戳#time.strftime ('%y-%m-%d ', Time.localtime ()) #将结构化时间转换成字符串时间#time.strptime (' 1990-03-12 ', '%y-%m-%d ') #将字符串时间转换为结构化时间#time.asctime () #将结构化时间-----> string Time#time.ctime () #将时间戳-----> string Time
Second, random module
ImportRandomPrint(Random.random ())#(0,1) float typePrint(Random.randint (1,3))#[1,3] int typePrint(Random.randrange (1,3))#[1,3] int type, Gu Tou regardless of tailPrint(Random.choice ([12, 23,'Hello']))#randomly fetching the contents of a listPrint(Random.sample ([12, 23,'Hello', 134],2))#randomly fetch a list of two itemsPrint(Random.uniform (1,3))#float in 1-3 floating-point integerL=[11,22,33,44]random.shuffle (L)#Shuffle OrderPrint(L)#Exercise: Verification CodedefValdate_code (): Ret="'     forIinchRange (5): Num=random.randint (0,9) Alfa=CHR (Random.randint (97,122)) ALFA2=CHR (Random.randint (65,90)) S=Random.choice ([str (num), ALFA,ALFA2]) ret=ret+sreturnretPrint(Valdate_code ())
Third, Hashlib

1, Algorithm Introduction

Python's hashlib provides a common digest algorithm, such as MD5,SHA1 and so on.

Abstract the algorithm is also called hash algorithm and hashing algorithm. It converts arbitrary-length data into a fixed-length data string (usually represented by a 16-binary string) through a function.

Abstract the algorithm is to calculate the fixed-length summary digest by the Digest function f () to the data of arbitrary length, in order to find out whether the original data has been tampered with.

Abstract algorithm making can point out whether the data has been tampered with, that is, because the sweet potato is a one-way function, it is easy to calculate f (data), but it is very difficult to push data by digest. Also, making a bit change to the original data will result in a completely different summary of the calculation.

Take the Common Digest algorithm MD5 as an example to calculate the MD5 value of a string:

Import hashlibmd5_obj=hashlib.md5 () md5_obj.update (b'hellowold')     # Summary content #  Digest return content hex return form (16 binary)print(md5_obj.hexdigest ())       #得到结果950a06c97a36396c573849ad7061ffcd

If the amount of data is large, you can call Update () multiple times in chunks, and the result is the same as the final calculation

MD5 = hashlib.md5 () md5.update(') md5.update ('python Hashlib? ' )print md5.hexdigest ()

2. Application of abstract algorithm

Summary algorithm application: File consistency check, login

Any site that allows users to log on will store the user name and password that the user is logged on to. How do I store a user name and password? method is stored in the database table:

Name    | password--------+----------Michael | 123456bob     | abc999alice   | alice2008

If the user password is saved in clear text, if the database is compromised, all users ' passwords fall into the hands of the hacker. In addition, the site operators can access the database, that is, to get all the user's password. The correct way to save a password is not to store the user's plaintext password, but instead to store a digest of the user's password, such as MD5:

Username | Password---------+---------------------------------Michael  | E10adc3949ba59abbe56e057f20f883ebob      | 878ef96e86145580c38c87f0410ad153alice    | 99b1c2188db85afee403b1536010c2c9

Consider such a situation, many users like to use 123456,888888,password these simple password, so, the hacker can calculate in advance these common password MD5 value, get a counter-push table:

' e10adc3949ba59abbe56e057f20f883e ': ' 123456 ' 21218cca77804d2ba1922c33e0151105 ': ' 888888 ' 5f4dcc3b5aa765d61d8327deb882cf99 ': ' Password '

This way, no need to crack, only need to compare the database MD5, hackers get the use of common password user account.

For the user, of course, do not use too simple password. But can we enhance the protection of simple passwords in program design?

Because the MD5 value of the common password is easy to calculate, so to ensure that the Stored user password is not the MD5 of the commonly used password, this method is implemented by adding a complex string to the original password, commonly known as "Add salt":

HASHLIB.MD5 ("Salt". Encode ("UTF8"))

Salt processing of the MD5 password, as long as the salt is not known by hackers, even if the user entered a simple password, it is difficult to MD5 the plaintext password.

But if two users all use the same simple password such as 123456, in the database, two identical MD5 values will be stored, which means that the password of the two users is the same. Is there a way for users with the same password to store different MD5?

If the user cannot modify the login, it is possible to calculate the MD5 by using the login as part of the salt, so that users who implement the same password also store different MD5.

Abstract algorithms are widely used in many places. Note that the digest algorithm is not an encryption algorithm and cannot be used for encryption (because plaintext cannot be reversed by the digest), but it is only used for tamper-proof, but its one-way computing feature determines that the user's password can be verified without storing the plaintext password.

Iv. OS Module

An OS module is an interface that interacts with the operating system

  

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work os.chdir ("dirname") Changes the current script working directory, equivalent to the shell under Cdos.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.path.abspath (path) returns the path normalized absolute path Os.path.dirname (path) that returns the directory of path. 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.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 common modules

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.