day06.2-Python中常用的内置模块
一. time模块:import time
1 import time 2 3 "1. 查看系统的时间戳信息" 4 t=time.time() 5 print(t) #1559136108.672717 6 7 "2. 显示系统的结构化当地时间(年 月 日 时 分 秒 一周中第几天 一年中第几天)" 8 t=time.localtime() 9 print(t)#time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=21, tm_min=23, tm_sec=56, tm_wday=2, tm_yday=149, tm_isdst=0) 10 print(t.tm_year) #2019 11 print(t.tm_wday) #2 12 13 "3. 显示系统的结构化世界时间" 14 t=time.gmtime() 15 print(t)#time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=13, tm_min=28, tm_sec=4, tm_wday=2, tm_yday=149, tm_isdst=0) 16 17 "4. 将结构化时间转换成时间戳" 18 t=time.mktime(time.localtime()) 19 print(t) #1559136597.0 20 21 "5. 将结构化时间转换成字符串时间" 22 t=time.strftime("%Y-%m-%d %X",time.localtime()) 23 print(t) #2019-05-29 21:32:16 24 25 "6. 将字符串时间转换成结构化时间" 26 t=time.strptime("2019:5:29:21:34:45","%Y:%m:%d:%X") 27 print(t)#time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=21, tm_min=34, tm_sec=45, tm_wday=2, tm_yday=149, tm_isdst=-1) 28 29 "7. 将结构化时间转换成固定格式的字符串时间" 30 t=time.asctime() 31 print(t) #Wed May 29 21:37:51 2019 32 33 "8. 将时间戳转换成固定格式的字符串时间" 34 t=time.ctime() 35 print(t) #Wed May 29 21:40:03 2019 36 37 "9. 线程运行推迟指定的时间,单位为秒" 38 time.sleep(1)
二. datetime模块:import datetime
1 import datetime 2 3 "1. 显示系统当前的字符串时间" 4 t=datetime.datetime.now() 5 print(t) #2019-06-04 20:56:31.669967
三. rand模块:import random
1 import random 2 3 "1. 在0~1之间随机生成一个浮点数" 4 n=random.random() 5 print(n) #0.07605310040756674 6 7 "2. 在指定范围内随机生成一个浮点数" 8 n=random.uniform(1,4) 9 print(n) #1.5884677589720386 10 11 "3. 在指定范围内随机生成一个整数" 12 n=random.randint(1,4) 13 print(n) #4 14 15 "4. 在序列中随机选取一个元素" 16 n=random.choice([1,'23',[4,5],'you']) 17 print(n) #23 18 19 "5. 随机从序列中选取指定个数的元素" 20 n=random.sample([1,'23',[4,5],'you'],2) 21 print(n) #[1, [4, 5]] 22 23 "6. 随机打乱序列的顺序" 24 ret=[1,'23',[4,5],"you"] 25 random.shuffle(ret) 26 print(ret) #[[4, 5], 1, 'you', '23']
四. os模块:import os
1 import os 2 3 "1. 获取当前Python脚本工作的目录" 4 p=os.getcwd() 5 print(p) #H:\MyPython\my_module 6 7 "2. 切换当前脚本的工作目录" 8 os.chdir('H:\MyPython') 9 print(os.getcwd()) #H:\MyPython 10 11 "3. 生成多层递归目录" 12 os.makedirs('H:\MyPython\my_module\makedirs1\makedirs2\makedirs3') 13 14 "4. 若当前目录为空,则删除当前目录并递归到上层目录,如上层目录也为空,则执行相同操作直至找到非空目录" 15 os.removedirs('H:\MyPython\my_module\makedirs1\makedirs2\makedirs3') 16 17 "5. 在当前路径下生成单层目录" 18 os.mkdir("makedir") 19 20 "6. 删除单级目录,若目标目录不为空则无法删除" 21 os.rmdir("makedir") 22 23 "7. 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印" 24 p=os.listdir(os.getcwd()) 25 print(p) #['my_module', 'run.py', 'test.py', '生成器'] 26 27 "8. 在当前目录下删除一个文件" 28 os.remove('run.py') 29 30 "9. 重命名当前目录下的文件/子目录" 31 os.rename('生成器','Builder') 32 33 "10. 查看文件信息,包括文件大小、上次查看时间、上次修改时间、创建时间" 34 p=os.stat('Builder') 35 print(p)#os.stat_result(st_mode=16895, st_ino=2251799813728966, st_dev=476857607, st_nlink=1, st_uid=0, st_gid=0, st_size=4096, st_atime=1556611563, st_mtime=1556611563, st_ctime=1554034077) 36 37 "11. 输出操作系统的路径的分隔符,Windows下为'\\',Linux下为'/'" 38 print(os.sep) #\ 39 40 "12. 输出当前平台使用的行终止符,Windows下为'\r\n',Linux下为'\n'" 41 print(os.linesep) #' ' 42 43 "13. 输出当前平台用于分割文件路径的字符串,Windows下为';',Linux下为':'" 44 print(os.pathsep) #; 45 46 "14. 返回文件/子目录的规范化路径" 47 p=os.path.abspath('test.py') 48 print(p) #H:\MyPython\test.py 49 50 "15. 返回文件/子目录的目录" 51 p=os.path.dirname('H:\MyPython\Bulider\bin.py') 52 print(p) #H:\MyPython 53 54 "16. 将路径分割成目录和文件名二元组返回" 55 p=os.path.split('H:\MyPython\Bulider\bin.py') 56 print(p) #('H:\\MyPython', 'Bulider\bin.py') 57 58 "17. 返回路径最后的文件名" 59 p=os.path.basename('H:\MyPython\Bulider\info.py') 60 print(p) #info.py 61 62 "18. 查看路径是否存在,若路径存在返回true,否则返回false" 63 p=os.path.exists(r'H:\MyPython\Builder\bin.py') 64 print(p) #True 65 66 "19. 查看路径是否为绝对路径,若是返回true,否则返回false" 67 p=os.path.isabs('H:\MyPython\Builder\bin.py') 68 print(p) #True 69 70 "20. 如果路径是一个已经存在的文件,返回true,否则返回false" 71 p=os.path.isfile(r'H:\MyPython\Builder\bin.py') 72 print(p) #True 73 74 "21. 如果路径是一个已经存在的目录,返回true,否则返回false" 75 p=os.path.isdir('H:\MyPython\Builder') 76 print(p) #True 77 78 "22. 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略" 79 p=os.path.join('H:\MyPython','Builder\web1','web2\web3') 80 print(p) #H:\MyPython\Builder\web1\web2\web3 81 82 "23. 返回目录所指路径/文件的最后存取时间" 83 p=os.path.getatime(r'H:\MyPython\Builder\bin.py') 84 print(p) #1556610936.0599964 85 86 "24. 返回目录所指路径/文件的最后修改时间" 87 p=os.path.getmtime(r'H:\MyPython\Builder\bin.py') 88 print(p) #1556610936.0609713
五. sys模块:import sys
1 import sys 2 3 "1. 命令行参数list,第一个元素是执行文件本身的路径,其余元素为程序执行时的输入元素" 4 p=sys.argv 5 print(p) #['H:/MyPython/my_module/bin.py'] 6 7 "2. 退出程序,正常退出时exit(0)" 8 sys.exit(n) 9 10 "3. 获取Python解释器的版本信息" 11 n=sys.version 12 print(n) #3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] 13 14 "4. 返回操作系统平台" 15 n=sys.platform 16 print(n) #win32 17 18 "5. 继续上次终端输出的位置刷新显示" 19 sys.stdout.write('@@') 20 print('zzzz') #@@zzzz 21 22 "6. 清空输出缓存" 23 sys.stdout.flush()
六. json模块:import json
json模块可用于跨开发语言间的序列化与反序列化。
把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Pyhton中叫做pickling,在其他语言中也被称之为serialization、marshalling、flattening等。数据经过序列化之后,就可以写入磁盘或者通过网络传输;把变量内容从序列化后的对象中重新读到内存的过程称为反序列化,即unpickling。
1 import json 2 3 "1. 输入数据转换成json字符串(pickling)" 4 data=[11,22,33,44,55] 5 string=json.dumps(data) 6 file=open('JSON.txt','w') 7 file.write(string) 8 9 "2. 提取json字符串中的数据(unpickling)" 10 file=open('JSON.txt','r') 11 string=file.read() 12 data=json.loads(string) 13 print(data) #[11, 22, 33, 44, 55]
七. xml模块:import xml.etree.ElementTree as ET
xml也是用于实现不同语言或程序之间进行数据交换的协议,与json差不多。
1. xml文件的遍历、修改与删除
city.html文件内容:
1 <?xml version="1.0"?> 2 <data> 3 <country name="Liechtenstein"> 4 <rank updated="yes">2</rank> 5 <year>2008</year> 6 <gdppc>141100</gdppc> 7 <neighbor name="Austria" direction="E"/> 8 <neighbor name="Switzerland" direction="W"/> 9 </country> 10 <country name="Singapore"> 11 <rank updated="yes">5</rank> 12 <year>2011</year> 13 <gdppc>59900</gdppc> 14 <neighbor name="Malaysia" direction="N"/> 15 </country> 16 <country name="Panama"> 17 <rank updated="yes">69</rank> 18 <year>2011</year> 19 <gdppc>13600</gdppc> 20 <neighbor name="Costa Rica" direction="W"/> 21 <neighbor name="Colombia" direction="E"/> 22 </country> 23 </data>
1 #bin.py文件内容 2 3 import xml.etree.ElementTree as ET 4 5 tree=ET.parse('city.html') 6 root=tree.getroot() 7 print(root.tag) #data 8 9 #遍历xml文档 10 for child in root: 11 print(child.tag,child.attrib) 12 for rechild in child: 13 print(' '*4,rechild.tag,rechild.text) 14 15 #只遍历year节点 16 for node in root.iter('year'): 17 print(node.tag,node.text) 18 19 #修改:所有year节点值加1,并添加修改标识 20 for node in root.iter('year'): 21 new_year=int(node.text)+1 22 node.text=str(new_year) 23 node.set('updated','yes') 24 tree.write('new_city1.html') 25 26 #删除:删除rank节点值大于50的城市 27 for node in root.findall('country'): 28 rank=int(node.find('rank').text) 29 if rank>50: 30 root.remove(node) 31 tree.write('new_city2.html')
2. 手动建立xml文件
1 import xml.etree.ElementTree as ET 2 3 new_xml=ET.Element('people_list') 4 5 people1=ET.SubElement(new_xml,'people',attrib={'enrolled':'yes'}) 6 name=ET.SubElement(people1,'name',attrib={'checked':'no'}) 7 name.text='alex' 8 age=ET.SubElement(people1,'age') 9 age.text='33' 10 sex=ET.SubElement(people1,'sex') 11 12 people2=ET.SubElement(new_xml,'people',attrib={'enrolled':'no'}) 13 name=ET.SubElement(people2,'name',attrib={'checked':'no'}) 14 name.text='bob' 15 age=ET.SubElement(people2,'age') 16 age.text='11' 17 18 tree=ET.ElementTree(new_xml) 19 tree.write('output.html')
八. re模块:import re
就其本质而言,正则表达式(re模块)是一种小型的、高度专业化的编程语言,通过re模块内嵌在Python中。正则表达式模式被编译成一系列的字节码,然后由C编写的驱动引擎执行。
1. 元字符:.^$*+?{}[]|()\
1 import re 2 3 "1. 通配符,可模糊匹配除换行符以外的所有字符" 4 ret=re.findall('a..x','abcxdefg') 5 print(ret) #['abcx'] 6 7 "2. 查找以指定字符串开头的子字符串" 8 ret=re.findall('^a..x','abcxdefg') 9 print(ret) #['abcx'] 10 11 "3. 查找以指定字符串结尾的子字符串" 12 ret=re.findall('d..g$','abcxdefg') 13 print(ret) #['defg'] 14 15 "4. 贪婪匹配就近重复出现多次(0~oo次)的字符" 16 ret=re.findall('alex*','abcdefalexxxx') 17 print(ret) #['alexxxx'] 18 ret=re.findall('alex*','abcdefale') 19 print(ret) #['ale'] 20 21 "5. 贪婪匹配就近重复出现多次(1~oo次)的字符" 22 ret=re.findall('alex+','abcdefalexxxx') 23 print(ret) #['alexxxx'] 24 ret=re.findall('alex+','abcdefale') 25 print(ret) #[] 26 27 "6. 贪婪匹配就近重复出现0~1次的字符" 28 ret=re.findall('alex?','abcdefalexxxx') 29 print(ret) #['alex'] 30 ret=re.findall('alex?','abcdefale') 31 print(ret) #['ale'] 32 33 "注:前面的'*''+''?'等都是贪婪匹配,也就是尽可能多地匹配,后面加'?'可以使其变成惰性匹配" 34 ret=re.findall('alex*?','abcdefgalexxxx') 35 print(ret) #['ale'] 36 ret=re.findall('alex+?','abcdefgalexxxx') 37 print(ret) #['alex'] 38 39 "7. 贪婪匹配就近重复出现0~n次的字符({0,}相当于*,{1,}相当于+,{0,,1}相当于?,{6}重复出现6次的字符)" 40 ret=re.findall('alex{6}','abcdefgalexxx') 41 print(ret) #[] 42 ret=re.findall('alex{6}','abcdefgalexxxxxx') 43 print(ret) #['alexxxxxx'] 44 ret=re.findall('alex{0,6}','abcdefgalexxx') 45 print(ret) #['alexxx'] 46 47 "8. 字符集" 48 ret=re.findall('x[yz]p','xypuuxzpuu') 49 print(ret) #['xyp', 'xzp'] 50 ret=re.findall('x[y*z]p','xypuuxzpuux*p') 51 print(ret) #['xyp', 'xzp', 'x*p'] 52 ret=re.findall('[x-z]','xyabcz') 53 print(ret) #['x', 'y', 'z'] 54 55 "注:在字符集中有特殊功能的字符有'-'、'^'、'\',分别为范围符号、非、转义符,除此之外,[]中所有内容都为普通字符没有特殊功能" 56 ret=re.findall('q[^a-z]','q123qxyzq5') 57 print(ret) #['q1', 'q5'] 58 59 "9. 转义符" 60 ret=re.findall('q[x\*]','qxxqxyuq*') 61 print(ret) #['qx', 'qx', 'q*'] 62 ret=re.findall('\*q','*qxxyup*qx') 63 print(ret) #['*q', '*q'] 64 ret=re.findall(r'I\b','I am LIST') 65 print(ret) #['I'] 66 ret=re.findall(r'c\\l','abc\le') 67 print(ret) #['c\\l'] 68 69 "10. 管道符,相当于逻辑或" 70 ret=re.findall('ka|bc','sdjkabcsf') 71 print(ret) #['ka', 'bc'] 72 73 "11. 字符分组" 74 ret=re.search('(?P<name>[a-z]+)(?P<age>\d+)','alex18bob23').group('age') 75 print(ret) #18对匹配结果进行分组 76 ret=re.findall('(abc)+','abcabcabc') 77 print(ret) #['abc']优先匹配分组内内容 78 ret=re.findall('(?:abc)+','abcabcabc') 79 print(ret) #['abcabcabc']取消分组内内容的优先级
2. re模块下的常用方法
1 import re 2 3 "1. 返回所有满足匹配条件的结果,放在列表中" 4 ret=re.findall('o','klay thompson') 5 print(ret) #['o', 'o'] 6 7 "2. 在字符串中查找匹配模式,只要找到第一个匹配之后以包的形式返回" 8 ret=re.search('o','klay thompson').group() 9 print(ret) #o 10 11 "3. 在字符串开头处查找匹配模式,若字符串开头符合匹配条件则以包的形式返回,否则报错" 12 ret=re.match('k','klay thompson').group() 13 print(ret) #k 14 15 "4. 分割字符串" 16 ret=re.split('[ab]','abc') 17 print(ret) #['', '', 'c']即先按'a'分割'abc'得到''和'bc',再按'b'分割'bc'得到''和'c' 18 19 "5. 字符替换" 20 ret=re.sub('\d+','AGE','alex34bob56') 21 print(ret) #alexAGEbobAGE 22 23 "6. 返回所有匹配的结果,放在迭代器中" 24 ret=re.finditer('\d','alex36bob38com42') 25 print(next(ret).group()) #3 26 print(next(ret).group()) #6 27 print(next(ret).group()) #3 28 print(next(ret).group()) #8 29 30 "注:re模块匹配完成后,优先显示分组内的内容" 31 ret=re.findall('www\.(baidu|google)\.com','1234www.google.com.5678') 32 print(ret) #['google']优先显示分组内内容 33 ret=re.findall('www\.(?:baidu|google)\.com','1234www.google.com.5678') 34 print(ret) #['www.google.com']取消分组的优先级
3. re模块下常用的通配符
- \d 匹配任何十进制数,相当于类[0-9];
- \D 匹配任何非数字字符,相当于类[^0-9];
- \s 匹配任何空白字符,相当于类[\t\n\r\f\v];
- \S 匹配任何非空白字符,相当于类[^\t\n\r\f\v];
- \w 匹配任何字母数字字符,相当于类[a-zA-Z0-9];
- \W 匹配任何非字母数字字符,相当于类[^a-zA-Z0-9];
- \b 匹配一个特殊字符边界,比如空格、&、#等。
九. logging模块:import logging
1. 日志文件的级别分类
日志文件共设有5个级别,各级别等级从低到高依次为:
- logging.debug('debug message');
- logging.info('info message');
- logging.warning('warning message'); #默认日志级别
- logging.error('error message');
- logging.critical('critical message').
默认情况下,Python的logging模块将日志打印到了标准输出中,且只显示了大于等于设定日志级别的日志(日志级别等级:CRITICAL>ERROR>WARNING>INFO>DEBUG),默认的日志格式为:日志级别,Logger名称,用户输出信息。
2. 设置日志文件参数的两种方法
- 方法1
1 import logging 2 3 logging.basicConfig( 4 level=logging.DEBUG, #日志级别 5 filename='logger.log', #日志文件,默认按追加模式写入日志信息 6 filemode='w', #以覆盖方式写入日志信息 7 format='%(asctime)s [%(lineno)d] %(message)s %(filename)s' #设置日志信息的格式 8 ) 9 10 logging.debug("debug") 11 logging.info("info") 12 logging.warning("warning") 13 logging.error("error") 14 logging.critical("critical")
1 #'logger.log'文件内容: 2 3 2019-06-19 21:19:42,167 [10] debug 1.py 4 2019-06-19 21:19:42,167 [11] info 1.py 5 2019-06-19 21:19:42,167 [12] warning 1.py 6 2019-06-19 21:19:42,167 [13] error 1.py 7 2019-06-19 21:19:42,167 [14] critical 1.py
- 方法2
1 import logging 2 def logger(): 3 logger=logging.getLogger() 4 5 fh=logging.FileHandler('test_logger') 6 ch=logging.StreamHandler() 7 8 fm=logging.Formatter('%(asctime)s %(message)s') 9 10 fh.setFormatter(fm) 11 ch.setFormatter(fm) 12 13 logger.addHandler(fh) 14 logger.addHandler(ch) 15 logger.setLevel(logging.DEBUG) 16 17 return logger 18 19 logger=logger() 20 21 logger.debug("debug") 22 logger.info("info") 23 logger.warning("warning") 24 logger.error("error") 25 logger.critical("critical")
1 #'test_logger'文件内容: 2 3 2019-06-19 21:49:49,962 debug 4 2019-06-19 21:49:49,962 info 5 2019-06-19 21:49:49,962 warning 6 2019-06-19 21:49:49,962 error 7 2019-06-19 21:49:49,962 critical
3. format参数中可能用到的格式化串
1 %(name)s #Logger的名字 2 %(levelno)s #数字形式的日志级别 3 %(levelname)s #文本形式的日志级别 4 %(pathname)s #调用日志输出函数的模块的完整路径名,可能没有 5 %(filename)s #调用日志输出函数的模块的文件名 6 %(module)s #调用日志输出函数的模块名 7 %(funcName)s #调用日志输出函数的函数名 8 %(lineno)d #调用日志输出函数的语句所在的代码行 9 %(created)f #当前时间,用UNIX标准的表示时间的浮点数表示 10 %(relativeCreated)d #自Logger创建以来到输出当前日志信息之间相差的毫秒数 11 %(asctime)s #字符串形式的当前时间,默认格式是"2019-6-19 22:05:11,969",逗号后面的是毫秒 12 %(thread)d #线程ID,可能没有 13 %(threadName)s #线程名,可能没有 14 %(process)d #进程ID,可能没有 15 %(message)s #用户输出的信息
4. 一个日志文件的例子及分析
1 import logging 2 3 logger1=logging.getLogger('mylogger') 4 logger1.setLevel(logging.DEBUG) 5 6 logger2=logging.getLogger('mylogger') 7 logger2.setLevel(logging.INFO) 8 9 fh=logging.FileHandler('test_logger') 10 ch=logging.StreamHandler() 11 12 logger1.addHandler(fh) 13 logger1.addHandler(ch) 14 15 logger2.addHandler(fh) 16 logger2.addHandler(ch) 17 18 logger1.debug('logger1 debug message') 19 logger1.info('logger1 info message') 20 logger1.warning('logger1 warning message') 21 logger1.error('logger1 error message') 22 logger1.critical('logger1 critical message') 23 24 logger2.debug('logger2 debug message') 25 logger2.info('logger2 info message') 26 logger2.warning('logger2 warning message') 27 logger2.error('logger2 error message') 28 logger2.critical('logger2 critical message')
1 #'test_logger'文件内容: 2 3 logger1 info message 4 logger1 warning message 5 logger1 error message 6 logger1 critical message 7 logger2 info message 8 logger2 warning message 9 logger2 error message 10 logger2 critical message
由代码输出结果可知,尽管设置了两个不同的日志句柄,但由于两个日志句柄具有相同的Logger名称,从而后面设置的句柄参数会覆盖前面已经设置的句柄参数(上例中logger2的日志级别覆盖了logger1的日志级别)。
十. configparser模块:import configparser
1. 配置文件的创建
1 import configparser 2 3 config=configparser.ConfigParser() 4 config['DEFAULT']={'ServerAliveInterval':'45', 5 'Compress':'yes', 6 'CompressionLevel':'9'} 7 8 config['bitbucket.org']={} 9 config['bitbucket.org']['User']='hg' 10 11 config['topsecret.server.com']={} 12 topsecret=config['topsecret.server.com'] 13 topsecret['Host Port']='50022' 14 topsecret['ForwardX11']='no' 15 16 config['DEFAULT']['ForwardX11']='yes' 17 18 with open('example.ini','w') as configfile: 19 config.write(configfile)
1 'example.ini'文件内容: 2 3 [DEFAULT] 4 serveraliveinterval = 45 5 compress = yes 6 compressionlevel = 9 7 forwardx11 = yes 8 9 [bitbucket.org] 10 user = hg 11 12 [topsecret.server.com] 13 host port = 50022 14 forwardx11 = no
2. 配置文件的查询、增加、删除与修改
1 import configparser 2 3 config=configparser.ConfigParser() 4 5 #--------------------------------查询-----------------------------------------# 6 print(config.sections()) #[] 7 8 config.read('example.ini') 9 print(config.sections()) #['bitbucket.org', 'topsecret.server.com'] 10 11 print('bytebong.com' in config) #False 12 print(config['bitbucket.org']['User']) #hg 13 print(config['DEFAULT']['compress']) #yes 14 print(config['topsecret.server.com']['ForwardX11']) #no 15 16 for key in config: 17 print(key) #DEFAULT #bitbucket.org #topsecret.server.com 18 19 print(config.options('bitbucket.org')) #['user', 'serveraliveinterval', 'compress', 'compressionlevel', 'forwardx11'] 20 print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compress', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] 21 print(config.get('bitbucket.org','compress')) #yes 22 23 #-------------------------------修改、增加、删除-------------------------------# 24 config.add_section('yuan') 25 26 config.remove_section('topsecret.server.com') 27 config.remove_option('bitbucket.org','user') 28 29 config.set('yuan','name','KD') 30 config.set('bitbucket.org','k1','11111') 31 32 config.write(open('i.example','w'))
1 'i.example'文件内容: 2 3 [DEFAULT] 4 serveraliveinterval = 45 5 compress = yes 6 compressionlevel = 9 7 forwardx11 = yes 8 9 [bitbucket.org] 10 k1 = 11111 11 12 [yuan] 13 name = KD
由代码输出结果可知,在遍历其他项中关键词的时候,DEFAULT中关键词会自动显示。这是因为DEFAULT的主要作用就是存放与其他项的共享关键词,从而在遍历的过程中DEFAULT中关键词也会显示。
十一. hashlib模块:import hashlib
对于哈希运算,Python 3中代替了md5模块和sha模块,主要提供了SHA1、SHA224、SHA256、SHA384、SHA512、MD5算法。
1 import hashlib 2 3 m=hashlib.md5('2019/7/15'.encode('utf-8')) #MD5算法加盐 4 5 m.update('hello'.encode('utf-8')) 6 print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592 7 8 m.update('alvin'.encode('utf-8')) 9 print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af 10 11 m2=hashlib.md5() 12 13 m2.update('helloalvin'.encode('utf-8')) 14 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af