今日主要内容:
1.hashlib模块补充
2.configparser模块
3.logging模块
4.collections模块
一.hashlib模块
补充1.使用hashlib进行文件一致性的验证
验证一段字符串与分段字符串加密后的md5是否一致
import hashlib md5obj = hashlib.md5() md5obj.update(b'hello ') md5obj.update(b'alex ') md5obj.update(b'I know your ') md5obj.update(b'password is alex3714') #df479511dcdf12b54f418e547f03f919 #需要注销以上的md5obj.update才能运行下面的,这样才能比对出真正的值来. md5obj.update(b'hello alex I know your password is alex3714') #df479511dcdf12b54f418e547f03f919 print(md5obj.hexdigest())
补充2:验证文件内容是否一致
import hashlib def check(filename): md5obj = hashlib.md5() with open(filename,'rb') as f: content = f.read() md5obj.update(content) return md5obj.hexdigest() #文件较小的时候可以用,大文件就没法用了.并且占内存 ret1 = check('file1') print(ret1) def check_1(filename): md5obj = hashlib.md5() with open(filename,'rb') as f1: while True: content = f1.read(1024) if content: md5obj.update(content) else: break return md5obj.hexdigest() #通用方法,可以节省很多内存,但是值是相同的 ret2 = check('file2') print(ret2) 结果: c19423ece13f682567616121c93fd124 c19423ece13f682567616121c93fd124
二.configparser #创建配置查看congfig配置文件的方法
举例:
import configparser config = configparser.ConfigParser() config['DEFAULT'] = { 'a':'45', 'CompresssionLevel':'9', 'Compression':'yes', 'ForwardX11':'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'5002' ,'ForwardX11':'no'} with open('example.ini','w') as f: config.write(f) #对象config的方法writer,把内容写到文件内.
对象config的其他方法
import configparser config = configparser.ConfigParser() config.read('example.ini') #对象读取配置文件内容 print(config.sections()) #打印配置文件内的段落标题,除第一个之外的(DEFAULT []) print('bitbucket.org' in config) # True 验证某个节是否在文件中 print('bytebong.com' in config) # False print(config['bitbucket.org']["user"]) # hg 查看某段下面的某个配置项的值 print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no print(config['bitbucket.org']) #<Section: bitbucket.org> for key in config['bitbucket.org']: # 注意,有default会默认default的键 print(key) print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value
原内容添加到新文件,并修改
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('yuan') #增加新部分标题为'元' config.remove_section('bitbucket.org') #删除bitbucket.org部分标题和内容 config.remove_option('topsecret.server.com',"forwardx11") #删除标题内的具体选项 config.set('topsecret.server.com','k1','11111') #在现有的部分内,添加选项 config.set('yuan','k2','22222') #添加新的部分,并设置一个选项 config.write(open('new2.ini', "w")) #将上述内容添加到新文件中
loggin模块
日志记录模块
它不能自己打印内容,只能根据程序员写的代码来完成功能
logging模块提供5中日志级别,从低到高一次:debug info warning error critical
默认打印屏幕从warning模式开始显示
默认只显示一些基础信息,我们还可以对显示的格式做一些配置
下例:
import logging logger = logging.getLogger()#对logging模块进行实例化 fh = logging.FileHandler('test.log',encoding = 'utf-8') #设置文件存储参数 sh = logging.StreamHandler() #开启屏幕显示 fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(fmt) # 格式和文件句柄或者屏幕句柄关联 sh.setFormatter(fmt) sh.setLevel(logging.WARNING) logger.addHandler(fh) #和logger关联的只有句柄 logger.addHandler(sh) logger.setLevel(logging.DEBUG) #设置日志记录级别 logger.debug('debug message') # debug 调试模式 级别最低 logger.info('info message') # info 显示正常信息 logger.warning('warning message') # warning 显示警告信息 logger.error('error message') # error 显示错误信息 logger.critical('critical message') #严重error错误信息
下面进入今天最后的一个模块
collections 新数据类型模块
在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等
namedtuple 命名字典型元组类型
from collections import namedtuple #等于import nametuple Point = namedtuple('Point',['x','y']) #输入的格式 p = Point(1,2) #实例化操作 print(p) #在内部对传入的值进行了一次赋值 print(p.x) print(p.y)
deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
from collections import deque q = deque(['a','b','c']) q.append('x') #默认从后插入 q.appendleft('y') #设置冲左插入 print(q)
OrderedDict
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
如果要保持Key的顺序,可以用OrderedDict
from collections import OrderedDict d = dict([('a',1),('b',2),('c',3)]) print(d) od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(od)