Day26

1、hashlib

下文中m=hashlib改为m=hashlib.md5

import hashlib
m=hashlib.md5()
m.update('123456'.encode='utf-8')
print(m.hexdigest())
#加盐
m=hashlib(b'bilibili')
m.update('123456'.encode='utf-8')
print(m.hexdigest)
#动态加盐
user=b'bilibili'
m=hashlib(user[::-1])
m.update('123456'.encode='utf-8')
print(m.hexdigest())
#文件的一致性校验
md5obj=hashlib.md5()
md5obj.update(b'hello')
md5obj.update(b'alex,')
md5obj.update(b'I know your')
md5obj.update(b'password is alex3714')
print(md5obj.hexdigest())
#一段字符串直接进行摘要和分成几段摘要的结果是相同的
View Code
import hashlib
def check(filename):
    md5obj=hashlib.md5()
    with open(filename,'rb') as f:
        content=f.read()
        md5obj.update(content)
    return md5obj.hexdigest()
def check(filename):
    md5obj=hashlib.md5()
    with open(filename,'rb')as f:
        while True:
            content=f.read(1024)
            if content:
                md5obj.update(content)
            else:
                break
    return md5obj.hexdigest()
ret1=check('file1')
ret2=check('file2')
print(ret1)
print(ret2)
View Code

序列化 把数据类型变成字符串

为什么要有序列化 因为在网络上和文件中能存在的只有字节

json  在所有语言中适用 只对有限的数据类型进行序列化 字典 列表 字符串 数字 元祖

    在多次写入dump数据进入文件的时候,不能通过load来取

pickle  只能在python中使用 对绝大多数数据类型都可以进行序列化

    在load的时候,必须拥有被load数据类型对应的类在内存里

dumps  序列化

loads  反序列化

dump  直接向文件中序列化

load  直接对文件反序列化

2、configparser模块

配置文件

import configparser
config=configparser.Configparser()
config['DEFAULT']={'a': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbucket.org']={'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini','w') as f:
    config.write(f)
View Code
import configparser
config = configparser.ConfigParser()
print(config.sections())        #  查看所有的节 但是默认不显示DEFAULT []
config.read('example.ini')
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
View Code
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('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"))
View Code

section 可以直接操作他的对象来获取所有的节信息

option  可以通过找到的节来查看多有的项

3、logging模块

log 日志
管理员
服务器上做操作
消费记录
淘宝

日志
给我们在内部操作的时候提供很多遍历
给用户提供更多的信息
在程序使用的过程中自己调试需要看的信息
帮助程序员排查程序的问题

logging模块 不会自动帮你添加日志的内容
你自己想打印什么 你就写什么

logging
简单配置
配置logger对象

# 简单配置
import logging
#默认情况下 只显示 警告 及警告级别以上信息
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %y %H:%M:%S',
                    filename = 'userinfo.log'
                    )
logging.debug('debug message')       # debug 调试模式 级别最低
logging.info('info message')         # info  显示正常信息
logging.warning('warning message')   # warning 显示警告信息
logging.error('error message')       # error 显示错误信息
logging.critical('critical message') # critical 显示严重错误信息
# 编码格式不能设置
# 不能同时输出到文件 和 屏幕
#配置logger对象
import logging
logger=logging.getLogger()    #实例化了一个logger对象
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)

#吸星大法
logging.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')

logging

logging 是记录日志的模块

它不能自己打印内容 只能根据程序员写的代码来完成功能

logging模块提供五种日志级别,从低到高依次:debug info warning error critical

默认从warning模式开始显示

只显示一些基础信息 我们还可以对显示的格式做一些配置

简单配置 配置模式basicConfig

问题:编码问题,不能同时输出到文件和屏幕

logger对象配置

首先创造logger对象

创造文件句柄 屏幕句柄

创造格式

使用文件句柄和屏幕句柄 绑定格式

logger对象和句柄关联

logger.setLevel

使用的时候logger.debug

4、collections模块

from collections import namedtuple
Point=namedtuple('Point',['x','y'])
p=Point(1,2)
print(p)
print(p.x)
print(p.y)
View Code
from collections import deque
#双端队列
dq = deque()
dq.append(1)
dq.append(2)
dq.append(3)
print(dq)
print(dq.pop())
print(dq.popleft())
dq.appendleft(4)
dq.appendleft(5)
print(dq)
View Code

import queue

队列 先进先出 fifo

计算机数据结构模型

栈 先进后出

计算机数据结构模型

dic = {'k1':'v1','k2':'v1','k3':'v1','k4':'v1'}
keys = list(dic.keys())
print(keys)
for k in keys:
    print(k,dic[k])

from collections import OrderedDict
dic = dict([('k1','v1'),('k2','v2')])
print(dic)

dic = OrderedDict([('k1','v1'),('k2','v2')])
print(dic)
View Code
原文地址:https://www.cnblogs.com/a352735549/p/8920825.html