7-3三个模块 hashlib ,logging,configparser和序列化
一 hashlib
主要用于字符串加密
1
import hashlib
md5obj=hashlib.md5() # 实例化一个md5摘要算法的对象
md5obj.update('alex3714'.encode('utf-8')) # 使用md5算法的对象来操作字符串
ret = md5obj.hexdigest() #获取算法的结果 hex+digest 16进制+消化
print(ret,type(ret)) #加盐
md5obj=hashlib.md5('hello'.encode('utf-8')) # 实例化一个md5摘要算法的对象,加盐
md5obj.update('alex3714'.encode('utf-8'))# 使用md5算法的对象来操作字符串
ret=md5obj.hexdigest()
print(ret) #动态加盐
username='hu'
md5obj=hashlib.md5(username.encode('utf-8'))
md5obj.update('alex3714'.encode('utf-8'))# 使用md5算法的对象来操作字符串里面必须是bytes类型
ret=md5obj.hexdigest()
print(ret)
二 logging日志模块
常用的格式是
# logger对象的方式配置
logger = logging.getLogger()
# 吸星大法 # 先创造一个格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 往文件中输入
fh = logging.FileHandler('log.log',encoding='utf-8') # 创造了一个能操作文件的对象fh
fh.setFormatter(formatter) # 高可定制化
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)
sh = logging.StreamHandler() #sh是在屏幕上面显示的
# sh.setFormatter(formatter1)
logger.addHandler(sh)
fh.setLevel(logging.ERROR) #文件里面显示error级别以上的
sh.setLevel(logging.DEBUG) #屏幕上面显示debug级别以上的 logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('程序出错了')
logger.critical('logger critical message')
三 configparser
#该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
1 用configparser写文件
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': '',
'ForwardX11':'yes'
}
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:
config.write(configfile)
2 用configparser查找文件
import configparser
config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
print(config.sections()) # []
config.read('example.ini')
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
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
四 序列化
1 概念
# 什么叫序列化呢?
# { '10100011':{'name':,age: ,class:},}
# 数据类型 —— 字符串的过程
# 什么时候要用序列化呢?
# 数据从内存到文件
# 数据在网络上传输 字节 - 字符串 - 字典
# python中的序列化模块都有哪些?
# json 通用的 支持的数据类型 list tuple dict
# pickle python中通用的 支持几乎所有python中的数据类型
# shelve python中使用的便捷的序列化工具
2 json
#dumps和loads是和内存交互的
#dump和load是和文件交互的
import json
dic={'k':'v'}
# print(type(dic))
# json_dic=json.dumps(dic) # 字典转字符串的过程 ——序列化
# print(json_dic)
# print(dic)
# print(type(json_dic))
# print(json.loads(json_dic)) #字符串 转回其他数据类型 —— 反序列化
注意:可以dump多次,但是不能多次load
怎样dump多条数据呢?
# 如果要dump多条数据
# 每一条数据先dumps一下 编程字符串 然后打开文件 write写进文件里 \n
# 读取的时候按照标志读取或者按行读
# 读出来之后 再使用loads with open('aaa','w')as f:
str_dic=json.dumps(dic)
f.write(str_dic+'\n')
f.write(str_dic + '\n')
f.write(str_dic + '\n')
with open('aaa')as f:
for line in f:
print(json.loads(line.strip()))
3 pickle
import pickle
class A:
def __init__(self,name):
self.name=name
alex=A('alex')
print(pickle.dumps(alex)) with open('b_pickle','wb')as f:
pickle.dump(alex,f)
pickle.dump(alex, f)
with open('b_pickle','rb')as f:
while True:
try:
obj=pickle.load(f)
print(obj.name)
except EOFError:
break
总结
#1.pickle支持更多的数据类型
# 2.pickle的结果是二进制
# 3.pickle在和文件交互的时候可以被多次load
7-3三个模块 hashlib ,logging,configparser和序列化的更多相关文章
- python之常用模块二(hashlib logging configparser)
摘要:hashlib ***** logging ***** configparser * 一.hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 摘要算法 ...
- time,datetime,random,os,sys,hashlib,logging,configparser,re模块
#-----time模块----- print(help(time)) #打印time帮助文档 print(time.time()) #打印时间戳 1569824501.6265268 time.sl ...
- python开发模块基础:异常处理&hashlib&logging&configparser
一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...
- python模块(shelve,xml,configparser,hashlib,logging)
1.1shelve模块 shelve 模块比pickle模块简单,只有一个open函数,返回类似字典对象,可读可写:key必须为字符串, 而值可以是python所支持的数据类型. shelve模块主要 ...
- s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译
时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...
- Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)
一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...
- 常用模块(hashlib,configparser,logging)
常用模块(hashlib,configparser,logging) hashlib hashlib 摘要算法的模块md5 sha1 sha256 sha512摘要的过程 不可逆能做的事:文件的一致性 ...
- 模块---hashlib、configparse、logging
一.hashlib模块 hashlib模块介绍:hashlib这个模块提供了摘要算法,例如 MD5.hsa1 摘要算法又称为哈希算法,它是通过一个函数,把任意长度的数据转换为一个长度固定的数据串,这个 ...
- 常用模块xml,shelve,configparser,hashlib
XML 什么XML:全称 可扩展标记语言 标记指的是代表某种含义的字符 XML<> 为什么需要XML 为能够在不同的平台间继续数据的交换 为了使交换的数据能让对方看懂 就需要按照一定的语法 ...
随机推荐
- 解决底部Button遮挡ListView最后一项内容的bug
项目中ListView和Button经常是一起使用的,用ListView来展示数据,用Button来提交修改的数据或对修改的数据进行确定操作. 假如使用线性布局的话ListView会盖住整个Butto ...
- htmlunit第一个爬虫演示 目标网址http://ent.sina.com.cn/film/
基本都要放弃了 springmvc 配置了htmlunit之后无法运行,都不能正常实例化webclient,但是突然想起来用maven应用程序测试一下 结果竟然就可以了.好吧,还是有希望的 大佬博客 ...
- springmvc jsp向controller传参,一直为null
怎么检查都无解 重启电脑好了
- HTML:如何将网页分为上下两个部分
1.使用table: <table> <tr> <td height="80%"><jsp:include page=" ...
- 解决git的the remote end hung up问题_百度经验
使用git更新或提交中途有时出现The remote end hung up unexpectedly的异常,特别是资源库在国外的情况下.此问题可能由网络原因引起. 工具/原料 git 方法/步骤 ...
- LintCode_133 最长单词
题目 给一个词典,找出其中所有最长的单词. 样例 在词典 { "dog", "google", "facebook", "inte ...
- 【JZOJ4710】【NOIP2016提高A组模拟8.17】Value
题目描述 输入 输出 样例输入 5 8 2 10 7 5 1 11 8 13 3 样例输出 27 数据范围 解法 选定一些物品a[1],a[2],a[3]-a[num],尝试交换a[i],a[j],那 ...
- docker相关教程【转】
https://www.w3cschool.cn/docker/docker-run-command.html 运行容器 https://www.runoob.com/docker/docker-im ...
- C++程序设计教材目录思维导图(增C++Primer)
正在做C++思维导图,大工程,比较艰苦. 先做了三个C++教材目录的思维导图.C++教材不等于C++,这个容易些.看思维导图,整理所学知识,这个可以会. 给出三张图,对应三种教材: 谭浩强. C++程 ...
- CentOS8.0-1905安装配置ftp服务器
关键词:CentOS8/RHEL8;安装配置FTP/安装配置VSFTPD;被动模式/PASV##CentOS8.0-1905发布后,尝试将FTP服务器迁移至新版本的CentOS中,但是测试过程中,在防 ...