zoukankan      html  css  js  c++  java
  • 7-3三个模块 hashlib ,logging,configparser和序列化

    一 hashlib

    主要用于字符串加密

     1 import hashlib
     2 md5obj=hashlib.md5() # 实例化一个md5摘要算法的对象
     3 md5obj.update('alex3714'.encode('utf-8')) # 使用md5算法的对象来操作字符串
     4 ret = md5obj.hexdigest() #获取算法的结果 hex+digest 16进制+消化
     5 print(ret,type(ret))
     6 
     7 #加盐
     8 md5obj=hashlib.md5('hello'.encode('utf-8')) # 实例化一个md5摘要算法的对象,加盐
     9 md5obj.update('alex3714'.encode('utf-8'))# 使用md5算法的对象来操作字符串
    10 ret=md5obj.hexdigest()
    11 print(ret)
    12 
    13 #动态加盐
    14 username='hu'
    15 md5obj=hashlib.md5(username.encode('utf-8'))
    16 md5obj.update('alex3714'.encode('utf-8'))# 使用md5算法的对象来操作字符串里面必须是bytes类型
    17 ret=md5obj.hexdigest()
    18 print(ret)

    二 logging日志模块

    常用的格式是

     1 # logger对象的方式配置
     2 logger = logging.getLogger()
     3 # 吸星大法
     4 
     5 # 先创造一个格式
     6 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     7 # 往文件中输入
     8 fh = logging.FileHandler('log.log',encoding='utf-8')   # 创造了一个能操作文件的对象fh
     9 fh.setFormatter(formatter) # 高可定制化
    10 logger.addHandler(fh)
    11 logger.setLevel(logging.DEBUG)
    12 sh = logging.StreamHandler() #sh是在屏幕上面显示的
    13 # sh.setFormatter(formatter1)
    14 logger.addHandler(sh)
    15 fh.setLevel(logging.ERROR) #文件里面显示error级别以上的
    16 sh.setLevel(logging.DEBUG)  #屏幕上面显示debug级别以上的
    17 
    18 logger.debug('logger debug message')
    19 logger.info('logger info message')
    20 logger.warning('logger warning message')
    21 logger.error('程序出错了')
    22 logger.critical('logger critical message')

    三 configparser 

    #该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

    1 用configparser写文件

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 
     5 config["DEFAULT"] = {'ServerAliveInterval': '45',
     6                       'Compression': 'yes',
     7                      'CompressionLevel': '9',
     8                      'ForwardX11':'yes'
     9                      }
    10 
    11 config['bitbucket.org'] = {'User':'hg'}
    12 
    13 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
    14 
    15 with open('example.ini', 'w') as configfile:
    16 
    17  config.write(configfile)

    2 用configparser查找文件

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 
     5 #---------------------------查找文件内容,基于字典的形式
     6 
     7 print(config.sections())        #  []
     8 
     9 config.read('example.ini')
    10 
    11 print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
    12 
    13 print('bytebong.com' in config) # False
    14 print('bitbucket.org' in config) # True
    15 
    16 
    17 print(config['bitbucket.org']["user"])  # hg
    18 
    19 print(config['DEFAULT']['Compression']) #yes
    20 
    21 print(config['topsecret.server.com']['ForwardX11'])  #no
    22 
    23 
    24 print(config['bitbucket.org'])          #<Section: bitbucket.org>
    25 
    26 for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    27     print(key)
    28 
    29 print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
    30 
    31 print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
    32 
    33 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

     1 #dumps和loads是和内存交互的
     2 #dump和load是和文件交互的
     3 import json
     4 dic={'k':'v'}
     5 # print(type(dic))
     6 # json_dic=json.dumps(dic) # 字典转字符串的过程 ——序列化
     7 # print(json_dic)
     8 # print(dic)
     9 # print(type(json_dic))
    10 # print(json.loads(json_dic))  #字符串 转回其他数据类型 —— 反序列化

    注意:可以dump多次,但是不能多次load

    怎样dump多条数据呢?

     1 # 如果要dump多条数据
     2 # 每一条数据先dumps一下 编程字符串 然后打开文件 write写进文件里 
    
     3 # 读取的时候按照标志读取或者按行读
     4 # 读出来之后 再使用loads
     5 
     6 with open('aaa','w')as f:
     7     str_dic=json.dumps(dic)
     8     f.write(str_dic+'
    ')
     9     f.write(str_dic + '
    ')
    10     f.write(str_dic + '
    ')
    11 with open('aaa')as f:
    12     for line in f:
    13         print(json.loads(line.strip()))

    3 pickle

     1 import pickle
     2 class A:
     3     def __init__(self,name):
     4         self.name=name
     5 alex=A('alex')
     6 print(pickle.dumps(alex))
     7 
     8 with open('b_pickle','wb')as f:
     9     pickle.dump(alex,f)
    10     pickle.dump(alex, f)
    11 with open('b_pickle','rb')as f:
    12     while True:
    13         try:
    14             obj=pickle.load(f)
    15             print(obj.name)
    16         except EOFError:
    17             break

    总结

    #1.pickle支持更多的数据类型
    # 2.pickle的结果是二进制
    # 3.pickle在和文件交互的时候可以被多次load

  • 相关阅读:
    怎样从基本原理解释复制型共享账本的价值
    BZOJ3223:文艺平衡树——超详细题解
    BZOJ3223:文艺平衡树——超详细题解
    BZOJ3223:文艺平衡树——超详细题解
    BZOJ3223:文艺平衡树——超详细题解
    my stackoverflow
    my stackoverflow
    my stackoverflow
    my stackoverflow
    STM32 Flash 永久用户数据空间
  • 原文地址:https://www.cnblogs.com/huningfei/p/9084440.html
Copyright © 2011-2022 走看看