Introduction to the Python module (i)

Source: Internet
Author: User
Tags local time sha1 timedelta

Modules allow you to logically organize your Python code snippets.

Assigning the relevant code to a module will make your code better and easier to understand.

The module is also a Python object, with a random name attribute used to bind or reference.

Simply put, the module is a file that holds the Python code. Modules can define functions, classes, and variables. The module can also contain executable code.

The modules are divided into three types:

    • Custom Modules
    • Built-in modules (also known as standard libraries)
    • Third-party modules (also known as third-party modules)

Custom modules:

That is, you write, create a. py file yourself to implement some functions called custom modules

Import module:

Python is used more and more widely, and to a certain extent relies on it providing programmers with a large number of modules to use, and if you want to use modules, you need to import them. There are several ways to import a module:

Python is used more and more widely, and to a certain extent relies on it providing programmers with a large number of modules to use, and if you want to use modules, you need to import them. There are several ways to import a module: 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 want to import the module hello.py, you need to put the command at the top of the script: a module will only be imported once, no matter how many times you execute the import. This prevents the import module from being executed over and over again. The FROM statement of the import file name Python lets you import a specified section from the module into the current namespace. The syntax is as follows for example, to import the XXX function of the module ZZZ, use the following statement: This declaration does not import the entire ZZZ module into the current namespace, it only introduces the xxx individual in the zzz to the global symbol table of the module that executes the declaration. From zzz import XXX It is also possible to import all the contents of a module into the current namespace, just use the following declaration: This provides an easy way to import all the items in a module. However, such statements should not be used too much. From module.xx.xx Import *

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
    • So the question is, is the module being imported based on that path as a benchmark? namely: Sys.path
#!/usr/bin/env/python#-*-coding:utf-8-*-import sys   #获取给脚本传入的参数print (sys.path) D:\python3.5\python.exe d:/ Untitled/python3/sys module. py[' D:\\untitled\\python3 ', ' d:\\untitled ', ' d:\\python3.5\\python35.zip ', ' D:\\python3.5\ \dlls ', ' d:\\python3.5\\lib ', ' d:\\python3.5 ', ' D:\\python3.5\\lib\\site-packages ']process finished with exit code 0
If the Sys.path path list does not have the path you want, it can be added by Sys.path.append (' path ').
Import syssys.path.append (' d:\\untitled\\python1\\day1.py ') print (Sys.path)
D:\python3.5\python.exe d:/untitled/python3/sys module. py[' D:\\untitled\\python3 ', ' d:\\untitled ', ' d:\\python3.5\\ Python35.zip ', ' d:\\python3.5\\dlls ', ' d:\\python3.5\\lib ', ' d:\\python3.5 ', ' d:\\python3.5\\lib\\site-packages ', ' D:\\untitled\\python1\\day1.py ']process finished with exit code 0

You can also go up to the download after the installation module is successfully installed, the module is automatically installed in a directory in Sys.path, such as:

/usr/lib/python2.7/site-packages/

Site-packages is a module that holds third-party installations

Built-in modules:

Time module:

Importing modules import time print (Time.time ()) #返回当前系统时间戳 1970 the number of seconds that the Linux system was born into the current execution result: 1463843836.9476368print (Time.ctime ()) # Output current system time execution results: Sat may 23:17:57 2016print (Time.ctime (Time.time () -86400)) #将当前时间减一天转为字符串格式 execution Result: Fri May 20 23:19:53 201 6 Print (Time.gmtime (Time.time () -86400)) #将当前时间转换成_time格式执行结果: Time.struct_time (tm_year=2016, tm_mon=5, tm_mday=20, Tm_hour=15, tm_min=21, tm_sec=43, tm_wday=4, tm_yday=141, tm_isdst=0) print (Time.localtime (Time.time ()-86400)) # local time conversion to strruct_time format execution results: Time.struct_time (tm_year=2016, tm_mon=5, tm_mday=20, tm_hour=23, tm_min=24, tm_sec=16, tm_ Wday=4, tm_yday=141, tm_isdst=0) print (Time.mktime (Time.localtime ())) #于time. LocalTime () function instead, the struct_ The time format is reversed to the local timestamp format execution result: 1463844332.0print (' Kaixin ') time.sleep (4) #时间间隔4秒print (' gege ') execution result #操作一遍就明白了kaixingegeprint ( Time.strftime ('%y-%m-%d%h:%m:%s ', Time.gmtime ())) #将struct_time格式转成指定的字符串格式执行结果: 2016-05-21 15:31:32print ( Time.strptime (' 2016-01-28 ', '%y-%m-%d ')) #将字符串格式转换成struct_time格式执行结果: Time.struct_time (tm_year=2016, tm_Mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=28, Tm_isdst=-1) 
Import datetime
Print (Datetime.date.today ())  #输出当前的日期执行结果: 2016-05-22print (Datetime.date.fromtimestamp (Time.time ()-84600)) # -84600 minus one day #输出前一天的时间执行结果: 2016-05-21current_time = Datetime.datetime.now () print (current_time)  #输出 current time execution results : 2016-05-22 00:15:15.434901print (Current_time.timetuple ()) #输出返回struct_time格式执行结果: Time.struct_time (tm_year=2016, Tm_mon=5, tm_mday=22, tm_hour=0, tm_min=15, tm_sec=15, tm_wday=6, tm_yday=143, tm_isdst=-1) print (current_time.replace (2015,10,10)) #输出2015-10-10 of the date the current time execution result: 2015-10-10 00:15:15.434901str_to_date = Datetime.datetime.strptime ("21/11/ 16:30 ","%d/%m/%y%h:%m ") print (str_to_date)   #将字符串转换成日期格式执行结果: 2006-11-21 16:30:00

New_data = Datetime.datetime.now () +datetime.timedelta (days=10) print (new_data)  #当前的日期加10天new_data = Datetime.datetime.now () +datetime.timedelta (days=-10) print (new_data) #当前的日期减10天new_data = Datetime.datetime.now () + Datetime.timedelta (hours = ten) print (new_data)  #当前时间-10 hours New_data = Datetime.datetime.now () +datetime.timedelta ( seconds = +) print (new_data)  #当前时间加120秒执行结果2016-06-01 00:09:36.2369872016-05-12 00:09:36.2369872016-05-22 10:09:36.2369872016-05-22 00:11:36.236987

Random module:

# import  random module, #验证码的操作random. Randint (1,99)   #随机数字temp = ' '   defines an empty string for I in range (6):  Loop 6 times    q = Random.randrange (0,4)  automatically generates a 0-4 random number    If q = = 3 or Q = = 1:    If the random number equals 3 or 1 generates lowercase letters        C2 = Random.randrang E (0,10)  generates a random number within 0--10        temp = temp + str (c2)   to the variable to add the ASCII code corresponding to the current number of characters    else:        C = Random.randrange (65,91) generates a random number within 65-91        z = chr (c)        temp = temp + Z  

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.stdin          input related sys.stdout         output related sys.stderror       error related

Progress bar:

Import Sysimport timefor i in range:    sys.stdout.write ("\ r")    sys.stdout.write ("%s%% | %s "% (int (i/30*100), int (i/30*100) * ' * '))    Sys.stdout.flush ()    Time.sleep (0.1)

Pickle Module

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

Pickle.dumps (obj): Serializes any object into a STR and writes the STR to the file

Pickle.loads (String): Deserialization out of object

Pickle.dump (Obj,file): Directly serializes the object and writes to the file

Pickle.load (file): Deserializing an object from a file

import pickleaccounts = {: {' name ': ' Alex LI ', ' email ': ' [EMA            Il protected] ', ' passwd ': ' abc123 ', ' balance ': 15000, ' phone ': 13651054608, ' Bank_acc ': { ' ICBC ': 14324234, ' CBC ': 235234, ' ABC ': 35235423}}, 1001: {' name ' : ' CaiXin Guo ', ' email ': ' [email protected] ', ' passwd ': ' abc145323 ', ' balance ':-15000, ' Phone ': 1345635345, ' Bank_acc ': {' ICBC ': 4334343,}},}f = open (' account.db ', ' WB ') f.write (pic Kle.dumps (Accounts)) f.close () Acc_file_name = ' account.db ' account_file = open (Acc_file_name, ' rb ') Account_dic = Pickle.loads (Account_file.read ()) account_file.close () account_dic[1000][' balance ']-=500x = open (Acc_file_name, ' WB ') X.write (Pickle.dumps (account_dic)) X.close () print (account_dic) f = open (' account.db ', ' RB ') account_db = Pickle.loads (F.read ()) print (account_db) 

DIC = {    ' k1 ': [up],    ' K2 ': [3,4]}f = open (' Test ', ' WB ') pickle.dump (dic,f) f.close () F = open (' Test ', ' RB ') Dic2 = Pickle.load (f) Print (Dic2) f.close ()

Hashlib Module
For encryption-related operations,
Import Hashlib # ######## MD5 ######## hash = HASHLIB.MD5 () hash.update (' admin ') print hash.hexdigest () # ######## SHA1 # # # # # # # hash = HASHLIB.SHA1 () hash.update (' admin ') print hash.hexdigest () # ######## sha256 ######## hash = hashlib.sha256 () ha Sh.update (' admin ') print hash.hexdigest ()  # ######## sha384 ######## hash = hashlib.sha384 () hash.update (' admin ') Print hash.hexdigest () # ######## sha512 ######## hash = hashlib.sha512 () hash.update (' admin ') print hash.hexdigest ()

Small exercise:

Import hashlibdef MD5 (ARG):    ooo = hashlib.md5 (bytes (' Kai;x,in ', encoding= ' Utf-8 '))    ooo.update (bytes (ARG, encoding= ' Utf-8 '))    return ooo.hexdigest () def login (user,pwd): With    open (' db ', ' R ', encoding= ' utf-8 ') as F:        for line in F:            U, P =line.strip (). Split (' | ')            if u = = user and P = = MD5 (PWD):                return truedef Register (USER,PWD):    with open (' db ', ' a ', encoding= ' utf-8 ') as F:        temp = user + ' | ' + MD5 (PWD)        f.write (temp) k = input (' 1, login; 2, register ') if k = = ' 2 ': User    = input (' Enter user name: ')    pwd = input (' Please enter password: ') ' C13/>register (user,pwd) elif k = = ' 1 ': User    = input (' Please enter user name: ')    pwd = input (' Please enter password: ')    r = Login (user,pwd) C17/>if r:        print (' login successful ')    else:        print (' Login failed ')

Introduction to the Python module (i)

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.