Python学习(十二)—— 常见模块

常见内置模块

time模块

时间戳(单位是秒,代表由1970年元旦凌晨至今过去的时间),常用于计算 .time():

1 import time
2 #时间戳,单位是s
3 print(time.time())
4 # 1583246063.46606

结构化时间 

(显示当地当前的精确时间 年月日...).localtime()

1 print(time.localtime())
2 # time.struct_time(tm_year=2020, tm_mon=3, tm_mday=3, tm_hour=22, tm_min=36, tm_sec=33, tm_wday=1, tm_yday=63, tm_isdst=0)

  可以取出想要的时间信息

1 t = time.localtime()
2 print(t.tm_wday) #周几是从周0开始算的
3 # 1
4 print(t.tm_year)
5 # 2020

(显示当前格林威治的精确时间 年月日...).gmtime():

1 g = time.gmtime()
2 print(g)
3 # time.struct_time(tm_year=2020, tm_mon=3, tm_mday=3, tm_hour=14, tm_min=41, tm_sec=47, tm_wday=1, tm_yday=63, tm_isdst=0)
4 print(g.tm_wday) #周几是从周0开始算的
5 # 1
6 print(g.tm_year)
7 # 2020

将结构化时间转化成对应的时间戳 .mktime()

1 print(time.mktime(time.localtime()))
2 # 1583246793.0

将结构化时间转换成字符串时间 .strftime()

1 print(time.strftime("%Y-%m_%d %X",time.localtime()))
2 # 2020-03_03 22:52:02

将字符串时间转换成结构化时间 .strptime()

1 print(time.strptime("2020:1:1:20:8:30","%Y:%m:%d:%X"))
2 # time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=20, tm_min=8, tm_sec=30, tm_wday=2, tm_yday=1, tm_isdst=-1)

将结构化时间转换成给定格式的时间,不得修改 .asctime() 

1 print(time.asctime())
2 # Tue Mar  3 22:57:48 2020

将时间戳转换成给定格式的时间,不得修改 .ctime()

1 print(time.ctime(time.time()))
2 # Tue Mar  3 23:00:18 2020

字符串时间

补充一个关于时间的模块 datetime

1 import datetime
2 print(datetime.datetime.now())
3 # 2020-03-03 23:02:47.361912

random模块

随机浮点型、浮点型范围、随机整型、随机整型的范围

1 import random
2 print(random.random())
3 # 0.3947431257812979
4 print(random.uniform(1,5))#指定范围
5 # 4.521865000424089
6 print(random.randint(4,10)) #指定范围
7 # 8
8 print(random.randrange(4,1000))
9 # 384

在可迭代对象内随机取一个

1 print(random.choice([11,33,44,66]))
2 # 44

在可迭代对象内随机取多个

1 print(random.sample([11,33,44,66],3))
2 # [66, 11, 44]

打乱次序(洗牌)

1 l = [11,33,44,66]
2 random.shuffle(l)
3 print(l)
4 # [11, 66, 33, 44]

举例:做验证码

 1 import random
 2 def v_code():
 3     ret = ""
 4     for i in range(5):
 5         num = random.randint(0,9)
 6         alf = chr(random.randint(65,122))
 7         s = str(random.choice([num,alf]))
 8         ret += s
 9       return ret
10 
11 print(v_code())
12 # sj232

os模块

os.getcwd() 获取当前工作的目录

os.chdir("dirname") 改变当前工作目录

1 import os
2 print(os.getcwd())
3 # D:PythonStudyPython全栈day22
4 os.chdir("test")
5 print(os.getcwd())
6 # D:PythonStudyPython全栈day22	est
7 os.chdir("..") #返回上一层
8 print(os.getcwd())
9 # D:PythonStudyPython全栈day22

os.curdir 返回当前目录

os.pardir 返回当前目录的父目录字符串名

1 os.curdir#返回当前目录
2 print(os.getcwd())
3 os.pardir #返回当前目录的父目录字符串名
4 print(os.getcwd())

os.makedirs("dirname1/dirname2") 生成多层递归目录

os.removedirs("dirname1") 若为空目录,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

os.mkdirs('dirname") 生成单级目录

os.rmdir("dirname") 删除单级空目录,若目录非空则无法删除且报错

1 # os.makedirs("dir1/dir2") 创建多级目录
2 os.rmdir("dir1/dir2")  #删除单级空目录

os.listdir("dirname") 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

os.remove() 删除一个文件

os.rename("oldname","newname") 重命名文件/目录

os.stat("path/filename") 获取文件/目录信息(创建时间、修改时间、节点数、设备、用户名、字节数...)

os.sep 输出操作系统特定的路径分隔符,win下为“\”,Linux为“/”

os.linesep 输出当前平台使用的行终止符,win下为“ ”,Linux为“ ”

os.pathsep 输出用于分割文件路径的字符串 

os.name 输出字符串指示当前的使用平台,win下为“nt”,Linux为“posix”

os.system("bash command") 运行shell命令,直接显示

os.environ 获取系统的环境变量

os.path.abspath(path) 返回path的绝对路径

os.path.split(path) 将path分割成目录和文件名二元组返回

os.path.dirname(path) 返回path的目录。 其实就是os.path.split(path)的第一个元素

os.path.basename() 返回path最后的文件名。如果path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素

1 print(os.path.split(r"D:PythonStudyPython全栈day22lesson1.py"))
2 # ('D:\PythonStudy\Python全栈\day22', 'lesson1.py')
3 print(os.path.dirname(r"D:PythonStudyPython全栈day22lesson1.py"))
4 # D:PythonStudyPython全栈day22
5 print(os.path.basename(r"D:PythonStudyPython全栈day22lesson1.py"))
6 # lesson1.py

os.path.exists(path) 如果path存在,返回True,否则False

os.path.isabs(path) 如果path是绝对路径,返回True,否则False

os.path.isfile(path) 如果path是一个存在的文件,返回True,否则False

os.path.isdir(path) 如果path是一个存在的目录,返回True,否则False

os.path.join(path[,path[,...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

1 a = "D:PythonStudyPython全栈"
2 b = "day22lesson1.py"
3 print(os.path.join(a,b))
4 # D:PythonStudyPython全栈day22lesson1.py

os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间

os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

system模块

sys.argv 命令行参数List,第一个元素是程序本身路径

sys.exit(n) 退出程序,正常退出时exit(0)

sys.version() 获取Python解释程序的版本信息

sys.maxint 最大的Int值

sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform 返回操作系统平台名称

进度条的例子

1 import time,sys
2 for i in range(10):
3     sys.stdout.write("*")
4     time.sleep(0.4)
5     sys.stdout.flush #刷新,立刻显示
6 # **********

json模块   

可以进行任何数据类型的转换(能够跨语言)

使用eval转换,但有局限性。

1 f = open("hello","r")
2 data = f.read()
3 print(data,type(data))
4 # {"name":"alex"} <class 'str'>
5 data = eval(data)
6 print(data["name"],type(data))
7 # alex <class 'dict'>

json.dumps() 任何输入类型都会变成字符串,字符串存在时,单引号会变成双引号

 1 import  json
 2 dic = {"alex":"18"}
 3 l = [11,22,33]
 4 num = 89
 5 tu= (1,"w")
 6 dic = json.dumps(dic)
 7 print(dic,type(dic))
 8 l = json.dumps(l)
 9 print(l,type(l))
10 num = json.dumps(num)
11 print(num,type(num))
12 tu = json.dumps(tu)
13 print(tu,type(tu))
14 # {"alex": "18"} <class 'str'>
15 # [11, 22, 33] <class 'str'>
16 # 89 <class 'str'>
17 # [1, "w"] <class 'str'>

写入字符串(使用json.dumps(data))

1 import json
2 f = open("new_hello","w")
3 data = json.dumps({'name':'alex'})
4 f.write(data) # json.dump({'name':'alex'},f)
5 print(data,type(data)) 
6 # new_hello {"name": "alex"}

json.loads() 变换为原来的数据类型

1 f = open("new_hello","r")
2 data = f.read()
3 print(data,type(data))
4 # {"name": "alex"} <class 'str'>
5 new_data = json.loads(data) # new_data = json.load(f)
6 print(new_data,type(new_data)) 
7 # {'name': 'alex'} <class 'dict'>

pickle模块

和json模块使用完全一样,结果转换为字节“bytes”,功能有局限性。

序列化:把对象(变量)从内存中变成可存储或传输的过程称为序列化。在Python中称为pickling,在其他语言上称为serialization,marshalling,flattening等。

序列化之后,可以把序列化后的内容写入磁盘,或者通过网络传输到其他机器上。

相反的过程称为反序列化,即unpickling。

shelve模块

类似pickle,使用更简单,有局限性。

1 import shelve
2 f = shelve.open(r"text1")
3 f["name"] = "alex"
4 f["internships"] = {1:"babycare",2:"assistance",3:"worker"}
5 #会写出三个名为text1的文件,内容肉眼不可识别
6 print(f.get("internships")[2])
7 # assistance

XML模块 xml.etree.ElementTree 

实现不同语言或程序之间进行数据交换的协议,类似json,但json使用更加简单。

查询功能:

 1 #!/usr/bin/env python 
 2 # -*- coding:utf-8 -*-
 3 import xml.etree.ElementTree as ET #简写
 4 
 5 tree = ET.parse("xml_lesson")
 6 root = tree.getroot()
 7 print(root.tag)
 8 # data
 9 #遍历标签
10 for i in root:
11     print(i)
12 # <Element 'country' at 0x0000020DF9496B38>
13 # <Element 'country' at 0x0000020D8864EA48>
14 # <Element 'country' at 0x0000020D8864EBD8>
15 for i in root:
16     print(i.tag)
17     # country
18     # country
19     # country
20 # 遍历标签
21 for i in root:
22     for j in i:
23         print(j.attrib)
24         # {'updated': 'yes'}
25         # {'updated': 'yes'}
26         # {}
27         # {'direction': 'E', 'name': 'Austria'}
28         # {'direction': 'W', 'name': 'Switzerland'}
29         # {'updated': 'yes'}
30         # {'updated': 'yes'}
31         # {}
32         # {'direction': 'N', 'name': 'Malaysia'}
33         # {'updated': 'yes'}
34         # {'updated': 'yes'}
35         # {}
36         # {'direction': 'W', 'name': 'Costa Rica'}
37         # {'direction': 'E', 'name': 'Colombia'}
38 #遍历标签包裹的内容
39 for i in root:
40     for j in i:
41         print(j.text)
42         # 2
43         # 2010
44         # 141100
45         # None
46         # None
47         # 5
48         # 2013
49         # 59900
50         # None
51         # 69
52         # 2013
53         # 13600
54         # None
55         # None
56 #只遍历year节点
57 for node in root.iter("year"):
58     print(node.tag,node.text)
59     # year 2010
60     # year 2013
61     # year 2013
View Code

修改功能:

 1 import xml.etree.ElementTree as ET #简写
 2 
 3 tree = ET.parse("xml_lesson")
 4 root = tree.getroot()
 5 print(root.tag)
 6 
 7 for node in root.iter("year"):
 8     new_year = int(node.text)+1
 9     node.text = str(new_year) #修改属性值
10     node.set("updated","yes") #修改标签
11 tree.write("abc.xml")
View Code

删除功能:

1 import xml.etree.ElementTree as ET #简写
2 
3 tree = ET.parse("xml_lesson")
4 root = tree.getroot()
5 for country in root.findall("country"):
6     rank = int(country.find("rank").text)
7     if rank > 50:
8         root.remove(country)
9 tree.write("aaa.xml")
View Code

创建xml文件

 1 import xml.etree.ElementTree as ET
 2 new_xml = ET.Element("namelist")
 3 name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
 4 age = ET.SubElement(name, "age", attrib={"checked": "no"})
 5 sex = ET.SubElement(name, "sex")
 6 sex.text = '33'
 7 name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
 8 age = ET.SubElement(name2, "age")
 9 age.text = '19'
10 
11 et = ET.ElementTree(new_xml)  # 生成文档对象
12 et.write("test.xml", encoding="utf-8", xml_declaration=True)
13 ET.dump(new_xml)  # 打印生成的格式
14 # <namelist><name enrolled="yes"><age checked="no" /><sex>33</sex></name><name enrolled="no"><age>19</age></name></namelist>
View Code

re模块

究其本质,正则表达式(或RE)是一种小型的高度专业化的编程语言。它内嵌在Python中,并通过re模块实现。re表达式模式被编译成一系列的字节码,然后由C编写的匹配引擎执行。

用途:实现模糊匹配

字符匹配:
1、普通字符:大多数字符和字母都和本身匹配

2、元字符:. ^ $ * + ? { } [ ] | ( )

    

. 通配符,除 以外任何字符都可以匹配,一个.代表一个字符

^  放在字符串的开头,代表必须从字符串的开头匹配

$ 放在字符串的结尾,代表必须从字符串的结尾匹配

* 按照左侧紧挨着的字符重复,重复0~∞次,贪婪匹配,在后面加?可以变为惰性匹配

+ 按照左侧紧挨着的字符重复,重复1~∞次,贪婪匹配,在后面加?可以变为惰性匹配

 ? 按照左侧紧挨着的字符重复,重复0~1次,贪婪匹配,在后面加?可以变为惰性匹配

 1 import re
 2 
 3 # . 通配符
 4 ret = re.findall("a..x","wqawlxweg")
 5 print(ret)
 6 # ['awlx']
 7 
 8 # ^ 放在字符串的开头,代表必须从字符串的开头匹配
 9 ret = re.findall("^a..x","wqawlxweg")
10 print(ret)
11 # []
12 ret = re.findall("^a..x","acwxwqawlxweg")
13 print(ret)
14 # ['acwx']
15 
16 # $ 放在字符串的结尾,代表必须从字符串的结尾匹配
17 ret = re.findall("a..x$","acwxwqawlawex")
18 print(ret)
19 # ['awex']
20 
21 # * 按照左侧紧挨着的字符重复,重复0~∞次
22 ret = re.findall("a*$","qaawxwqawlawexaaa")
23 print(ret)
24 # ['aaa', ''] #没匹配到也算"
25 ret = re.findall("alex*","wxwqawlawexale")
26 print(ret)
27 # ['ale'] #没匹配到也算"
28 
29 # + 按照左侧紧挨着的字符重复,重复1~∞次
30 ret = re.findall("a+$","qaawxwqawlawexaaa")
31 print(ret)
32 # ['aaa']
33 
34 # ? 按照左侧紧挨着的字符重复,重复0~1次
35 ret = re.findall("alex?","wxwqawlawexalexxxx")
36 print(ret)
37 # ['alex']
38 ret = re.findall("alex??","wxwqawlawexalexxxx")
39 print(ret)
40 # ['ale']
View Code

{ } 任意方式重复匹配

  --{0,} == *

  --{1,} == +

  --{0,1} == ?

 | 代表或的意思,符号的左边、右边都进行匹配

1 ret = re.findall(r"ka|b","lwakawnngeowngbc")
2 print(ret)
3 # ['ka', 'b']
4 ret = re.findall(r"ka|bcd","lwakawnn|geowngbc")
5 print(ret)
6 # ['ka']
View Code

  转义符号 

  用加元字符,可以把元字符变成普通字符

  用加普通字符,可以让普通字符实现特殊功能:

    d 匹配任何十进制数

    D 匹配任何非数字字符

    s 匹配任何空白符号

    S 匹配任何非空白符号

    w 匹配任何字母数字字符

    W 匹配任何非字母数字字符

     匹配一个特殊字符边界,比如空格,&,#等

1 ret = re.findall("I","www I am Iist")
2 print(ret)
3 # []
4 ret = re.findall(r"I","www I am Iist")
5 print(ret) #由于Python自身具有转义功能,导致传到re时符号已经改变,加r表示Python不进行转义
6 # ['I']
7 ret = re.findall("I\b","www I am Iist")
8 print(ret) #一个/代表转义,两个//表示转回原义
9 # ['I']

[ ] 是字符集,内部除了三个符号以外都是普通字符

  1、 -代表范围

  2、 ^代表非

  3、 转义符号

 re模块的分组功能:

 使用()分组,一旦分组以后,Python默认关注()内的内容

可以使用(?:)来降低优先级,从而得到全部结果

1 ret = re.findall("www.(baidu).com","awenwww.baidu.comwe")
2 print(ret)
3 # ['baidu']
4 ret = re.findall("www.(baidu|163).com","aw163enwww.baidu.comwe")
5 print(ret)
6 # ['baidu']
7 ret = re.findall("www.(?:baidu).com","awenwww.baidu.comwe")
8 print(ret)
9 # ['www.baidu.com']
View Code

有名分组

1 ret = re.search("(?P<name>[a-z]+)d+","alex25cindy55")
2 print(ret.group())
3 # alex25
4 print(ret.group("name"))
5 # alex
6 ret = re.search("(?P<name>[a-z]+)(?P<age>d+)","alex25cindy55")
7 print(ret.group("age"))
8 # 25
View Code

注意:

search 匹配成功,返回对象,匹配失败,返回空。search只找第一次满足条件的,一旦找到不再继续。

 1 ret = re.search("(?P<name>w+)","abcdee")
 2 print(ret)
 3 print(ret.group())
 4 # <re.Match object; span=(0, 6), match='abcdee'>
 5 # abcdee
 6 ret = re.search(r"d+","abc15dee34")
 7 print(ret)
 8 print(ret.group())
 9 # <re.Match object; span=(3, 5), match='15'>
10 # 15
View Code

match 匹配成功,返回对象,匹配失败,返回空。但match只从开始匹配,相当于在search里加^

split 分割

 

sub 替换

1 ret = re.sub("d+","A","sd12ne345nnie56")
2 print(ret)
3 # sdAneAnnieA
4 ret = re.sub("d+","A","sd12ne345nnie56",2)
5 print(ret)
6 # sdAneAnnie56
View Code

subn 替换且返回一个元组,包含替换的结果和替换的次数

1 ret = re.subn("d+","A","sd12ne345nnie56")
2 print(ret)
3 # ('sdAneAnnieA', 3)
View Code

compile 用于给定规则

1 com = re.compile("d+")
2 ret = com.findall("12nasw335eng23")
3 print(ret)
4 # ['12', '335', '23']
View Code

finditer 结果拿到一个迭代器

logging模块  日志模块 

basicConfig()模式

 日志级别:

debug

info

warning

error

critical

1 import logging
2 logging.debug("debug message")
3 logging.info("info message")
4 logging.warning("warning message")
5 logging.error("error message")
6 logging.critical("critical message")
7 # WARNING:root:warning message
8 # ERROR:root:error message
9 # CRITICAL:root:critical message

 通过调节参数来控制级别

 1 import logging
 2 logging.basicConfig(
 3     level = logging.DEBUG
 4 )
 5 logging.debug("debug message")
 6 logging.info("info message")
 7 logging.warning("warning message")
 8 logging.error("error message")
 9 logging.critical("critical message")
10 # DEBUG:root:debug message
11 # INFO:root:info message
12 # WARNING:root:warning message
13 # ERROR:root:error message
14 # CRITICAL:root:critical message

也可以存储到文件中,默认是追加模式

 1 import logging
 2 logging.basicConfig(
 3     level = logging.DEBUG,
 4     filename = "logging.log"
 5 )
 6 logging.debug("debug message")
 7 logging.info("info message")
 8 logging.warning("warning message")
 9 logging.error("error message")
10 logging.critical("critical message")
11 # logging.log
12 # DEBUG:root:debug message
13 # INFO:root:info message
14 # WARNING:root:warning message
15 # ERROR:root:error message
16 # CRITICAL:root:critical message
View Code

可以更改为修改模式

1 import logging
2 logging.basicConfig(
3     level = logging.DEBUG,
4     filename = "logging.log",
5     filemode = "w"
6 )
View Code

用format指定handler使用的日志显示格式

 1 import logging
 2 logging.basicConfig(
 3     level = logging.DEBUG,
 4     format = "%(asctime)s [%(lineno)s] %(filename)s %(message)s"
 5 )
 6 logging.debug("debug message")
 7 logging.info("info message")
 8 logging.warning("warning message")
 9 logging.error("error message")
10 logging.critical("critical message")
11 # 2020-03-06 11:53:05,762 [8] logging test.py debug message
12 # 2020-03-06 11:53:05,762 [9] logging test.py info message
13 # 2020-03-06 11:53:05,763 [10] logging test.py warning message
14 # 2020-03-06 11:53:05,763 [11] logging test.py error message
15 # 2020-03-06 11:53:05,763 [12] logging test.py critical message
View Code

logger()对象模式  ☆

 1 import logging
 2 logger = logging.getLogger()
 3 fh = logging.FileHandler("test_log") #存到文件里
 4 ch = logging.StreamHandler() #输出到屏幕上
 5 fm = logging.Formatter("%(asctime)s [%(lineno)s] %(filename)s %(message)s")
 6 
 7 fh.setFormatter(fm)
 8 ch.setFormatter(fm)
 9 logger.addHandler(fh)
10 logger.addHandler(ch)
11 logger.setLevel("DEBUG")
12 logger.debug("debug message")
13 logger.info("info message")
14 logger.warning("warning message")
15 logger.error("error message")
16 logger.critical("critical message")
17 # 2020-03-06 12:47:42,772 [12] logging test.py debug message
18 # 2020-03-06 12:47:42,773 [13] logging test.py info message
19 # 2020-03-06 12:47:42,773 [14] logging test.py warning message
20 # 2020-03-06 12:47:42,773 [15] logging test.py error message
21 # 2020-03-06 12:47:42,773 [16] logging test.py critical message

configparser模块

目的是配置文件的解析

 生成: 

 1 #!/usr/bin/env python 
 2 # -*- coding:utf-8 -*-
 3 import configparser
 4 
 5 config = configparser.ConfigParser() #config = {}
 6 config["DEFAULT"] = {'ServerAliveInterval': '45',
 7                      'Compression': 'yes',
 8                      'CompressionLevel': '9'}
 9 
10 config['bitbucket.org'] = {}
11 config['bitbucket.org']['User'] = 'hg'
12 config['topsecret.server.com'] = {}
13 topsecret = config['topsecret.server.com']
14 topsecret['Host Port'] = '50022'  # mutates the parser
15 topsecret['ForwardX11'] = 'no'  # same here
16 config['DEFAULT']['ForwardX11'] = 'yes' 
17 with open('example.ini', 'w') as configfile:
18     config.write(configfile)
19     # [DEFAULT]
20     # serveraliveinterval = 45
21     # compression = yes
22     # compressionlevel = 9
23     # forwardx11 = yes
24     # 
25     # [bitbucket.org]
26     # user = hg
27     # 
28     # [topsecret.server.com]
29     # host
30     # port = 50022
31     # forwardx11 = no

修改功能:

  查询

 1 import configparser
 2 config = configparser.ConfigParser()
 3 
 4 config.read("example.ini")
 5 print(config.sections()) #只打印非[DEFAULT]
 6 # ['bitbucket.org', 'topsecret.server.com']
 7 print("byte.org" in config) #判断是否在块内
 8 # False
 9 print(config["bitbucket.org"]["User"]) #大小写不敏感
10 # hg
11 for key in config["bitbucket.org"]: #会加上DEFAULT的key
12     print(key)
13     # user
14     # serveraliveinterval
15     # compression
16     # compressionlevel
17     # forwardx11
18 print(config.options("bitbucket.org")) #输出成列表格式
19 #['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
20 print(config.items("bitbucket.org")) #拿出键值对,以元组格式
21 #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
22 print(config.get("bitbucket.org","compression")) #DEFAULT相当于在任何块里
23 # yes
View Code

  增删改

1 import configparser
2 config = configparser.ConfigParser()
3 config.read("example.ini")
4 config.add_section("yuan") #加块
5 config.set("yuan","k1","1111")#加键值对
6 config.remove_section("bitbucket.org") #删除块
7 config.remove_option("yuan","k1")#删除键值对
8 config.write(open("i.cfg","w")) #写在新文件里
View Code

hashlib模块

  用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供SHA1, SHA224, SHA256, SHA384, SHA512, MD5算法

md5 加密

1 import hashlib
2 obj = hashlib.md5() #加密,不能反解
3 obj.update("hello".encode("utf8"))
4 print(obj.hexdigest())
5 # 5d41402abc4b2a76b9719d911017c592
6 # 比较的时候只能密文对密文

在一个程序中,第一次加密的结果会影响第二次加密的结果

1 obj = hashlib.md5() #加密,不能反解
2 obj.update("hello".encode("utf8"))
3 print(obj.hexdigest())
4 # 5d41402abc4b2a76b9719d911017c592
5 # 比较的时候只能密文对密文
6 obj.update("root".encode("utf8"))
7 print(obj.hexdigest())
8 # e206121dbbe984f3bc6c6448846ed8cd

  

1 import hashlib
2 obj = hashlib.md5() #加密,不能反解
3 obj.update("helloroot".encode("utf8"))
4 print(obj.hexdigest())
5 # e206121dbbe984f3bc6c6448846ed8cd

SHA256使用与MD5一致,只是需要花费更多时间

 

原文地址:https://www.cnblogs.com/jennifer224/p/12405614.html