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 为能够在不同的平台间继续数据的交换 为了使交换的数据能让对方看懂 就需要按照一定的语法 ...
随机推荐
- 在 IE 选项那提示 ”某些设置由系统管理员进行管理” 解决
运行 regedit 打开注册表 修改注册表值HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Interne ...
- jeecms9自定义标签以及使用新创建的数据库表
转载 https://blog.csdn.net/nice_meng/article/details/89179089 本系统使用的是jeecmsv9版本,收集网上知识后,进行个人汇总 首先,自己创建 ...
- jsp页面el表达式<c:choose> <c:when的用法
等于 是if else <c:choose> <c:when test="${paginationModel.py_province != ''}"> 如果 ...
- 洛谷P1080 [NOIP2012提高组D1T2]国王游戏 [2017年5月计划 清北学堂51精英班Day1]
P1080 国王游戏 题目描述 恰逢 H 国国庆,国王邀请 n 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右 手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 n 位大臣排 ...
- truncate 、delete、drop的区别
TRUNCATE TABLE 在功能上与不带 Where 子句的 Delete 语句相同:二者均删除表中的全部行.但 TRUNCATE TABLE 比 Delete 速度快,且使用的系统和事务日志资源 ...
- JavaScript字符串、数组、对象方法总结
字符串方法 示例字符串: const str = "hello,kitty,hello,vue "; 一.基本方法 charAt(n) 返回指定索引的字符 charCodeAt(n ...
- win10下安装mongodb(解压版)
首先到官网下载安装包.(https://www.mongodb.com/download-center#community) 1.创建mongodb目录 2.配置文件mongodb.config 3. ...
- 微服务Eureka使用详解
Eureka是spring cloud中的一个负责服务注册与发现的组件.遵循着CAP理论中的A(可用性)P(分区容错性). 一个Eureka中分为eureka server和eureka client ...
- 前端框架中 “类mixin” 模式的思考
"类 mixin" 指的是 Vue 中的 mixin,Regular 中的 implement 使用 Mixin 的目的 首先我们需要知道为什么会有 mixin 的存在? 为了扩展 ...
- iOS开发——你真的会用SDWebImage?
http://www.cocoachina.com/ios/20160503/16064.html 本文授权转载,作者:hosea_zhou(简书) SDWebImage作为目前最受欢迎的图片下载第三 ...