zoukankan      html  css  js  c++  java
  • 第十九章 模块 random、json、pickle、hashlib、hmac、shutil、shevele

    1.random:随机数

    random.random ()      (0,1)   0与1之间的随机float数

    random.randint ()  [1,10)  1与10之间的随机整数

    random.randrange ()  (1,10)  1与9之间的随机整数

    random.uniform ()  (1,10)  1与10之间的float数

    random.choice (item)  单列集合随机选择1个  (item  可循环对象)

    random.sample (item,n)  单列集合随机选择n个 ( item  可循环对象)

    random.shuffle (item)  洗牌单列集合(打散)item  (可循环对象)

    2.json:序列化

     为什么有很多序列化和反序列化模块
     因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化
     只有序列化存储后,必须有对应的反序列化,才能保证存储的数据能被重新读取使用

     什么是序列化:对象 => 字符串
     为什么序列化:存 或 传
     为什么要反序列化:再次使用
     为什么有很多序列化模块:存与取的算法可以多种多样,且要配套

    json语言,是一种有语法规范的字符串,用来存放数据的,完成各种语言之间的数据交互

      1、就是{ }与[  ]的组合,{ }存放双列信息(类比字典),[  ]存放单列信息(类比列表)

      2、{ }的key必须是字符串,必须用 "  "(双引号)包裹

      3、{ }与[  ]中支持的值的类型:dict  |  list  |  int  |  float  |  bool  |  null  |  str

    序列化:将对象转换为字符串

      dumps:将对象直接序列化成字符串

      dump: 将对象序列化成字符串存储到文件中

    例:

    obj = {'name': 'Owen', "age": 18, 'height': 180, "gender": "男"}

    re=json.dumps(obj,ensure_ascii=False)     # 取消默认ascii编码,同该文件的编码 utf-8 py3

     print(re)                                                             默认,py2规定文件头

    with open('x.txt',  'w'  ,  encoding='urf-8') as wf:

      json.dump(obj, wf ,  ensure_ascii=False)      (结果在x文件中查看)

    发序列化:将字符串转换成对象

    json_str = ' {"name": "Owen", "age": 18, "height": 180, "gender": "男"} '

    re=json.loads(json_str,encoding='utf-8')   (默认跟当前文件被解释器执行的编码走)

    print(re,type(re))

    with open('x.txt', 'r' ,encoding='utf-8' ) as rf

        re=json.roda(rf)

        print(re,type(re))

    3.pickle:序列化(pickel与json的用法相同但功能不同)

     为什么有很多序列化和反序列化模块
     因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化
     只有序列化存储后,必须有对应的反序列化,才能保证存储的数据能被重新读取使用

     什么是序列化:对象 => 字符串
     为什么序列化:存 或 传
     为什么要反序列化:再次使用
     为什么有很多序列化模块:存与取的算法可以多种多样,且要配套

    import pickle
    obj = {"name": 'Owen', "age": 18, "height": 180, "gender": "男"}

    序列化

    r1 = pickle.dump( obj )

    print (r1)

    with open ('2.txt','wb' ) as wf:

      pickle.dump (obj,wf)

    反序列化

    r1 = pickle.dumps(obj)
    print(r1)
    with open('2.txt', 'wb') as wf:
      pickle.dump(obj, wf)

    反序列化

    with open('2.txt', 'rb') as rf:
      data = rf.read()
      o1 = pickle.loads(data)
      print(o1, type(o1))

    rf.seek(0, 0)   # 游标移到开头出现读
    o2 = pickle.load(rf)
    print(o2, type(o2))

    4.hashlib:加密

     不可逆加密:没有解密的加密方式 md5
     解密方式:碰撞解密
     加密的对象:用于传输的数据(字符串类型数据)

    一次加密:
     1.获取加密对象 hashlib.md5() => lock_obj
     2.添加加密数据 lock_obj.update(b'...') ... lock_obj.update(b'...')
     3.获取加密结果 lock.hexdigest() => result

    lock = hashlib.md5(b'...')
    lock.update(b'...')

    lock.update(b'...')
    res = lock.hexdigest()
    print(res)

    加盐加密
     1.保证原数据过于简单,通过复杂的盐也可以提高解密难度
     2.即使被碰撞解密成功,也不能直接识别盐与有效数据
     lock_obj = hashlib.md5()
    lock_obj.update(b'goodgoodstudy')
    lock_obj.update(b'123')
    lock_obj.update(b'daydayup')
    res = lock_obj.hexdigest()
    print(res)

     了了解:其他算法加密
    lock_obj = hashlib.sha3_256(b'1')
    print(lock_obj.hexdigest())
    lock_obj = hashlib.sha3_512(b'1')
    print(lock_obj.hexdigest())

    6.hmac:加密

    import hmac
    hmac.new(arg) # 必须提供一个参数
    cipher = hmac.new('加密的数据'.encode('utf-8'))
    print(cipher.hexdigest())

    cipher = hmac.new('前盐'.encode('utf-8'))
    cipher.update('加密的数据'.encode('utf-8'))
    print(cipher.hexdigest())

    cipher = hmac.new('加密的数据'.encode('utf-8'))
    cipher.update('后盐'.encode('utf-8'))
    print(cipher.hexdigest())

    cipher = hmac.new('前盐'.encode('utf-8'))
    cipher.update('加密的数据'.encode('utf-8'))
    cipher.update('后盐'.encode('utf-8'))
    print(cipher.hexdiges

    7.shutil:文件操作

     基于路径的文件复制:
    shutil.copyfile('source_file', 'target_file')

     基于流的文件复制:
    with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
    shutil.copyfileobj(r, w)

     递归删除目标目录
    shutil.rmtree('target_folder')

     文件移动
    shutil.move('old_file', 'new_file')

     文件夹压缩
     file_name:被压缩后形成的文件名 format:压缩的格式 archive_path:要被压缩的文件夹路径
    shutil.make_archive('file_name', 'format', 'archive_path')

     文件夹解压
     unpack_file:被解压文件 unpack_name:解压后的名字 format解压格式
    shutil.unpack_archive('unpack_file', 'unpack_name', 'format')

    8.shelve:序列化文件操作

     将序列化文件操作dump与load进行封装
    shv_dic = shelve.open("target_file") # 注:writeback允许序列化的可变类型,可以直接修改值
     序列化:存
    shv_dic['key1'] = 'value1'
    shv_dic['key2'] = 'value2'

     文件这样的释放
    shv_dic.close()

     

    shv_dic = shelve.open("target_file", writeback=True)
     存 可变类型值
    shv_dic['info'] = ['原数据']

     取 可变类型值,并操作可变类型
     将内容从文件中取出,在内存中添加, 如果操作文件有writeback=True,会将内存操作记录实时同步到文件
    shv_dic['info'].append('新数据')

    反序列化:取
    print(shv_dic['info']) # ['原数据', '新数据']

    shv_dic.close()

     

  • 相关阅读:
    Azkaban的使用
    Azkaban安装
    Kafka 启动失败,报错Corrupt index found以及org.apache.kafka.common.protocol.types.SchemaException: Error reading field 'version': java.nio.BufferUnderflowException
    Kafka 消费者设置分区策略及原理
    Kafka利用Java API自定义生产者,消费者,拦截器,分区器等组件
    zookeeper群起总是有那么几个节点起不来的问题解决
    flume 启动agent报No appenders could be found for logger的解决
    Flume 的监控方式
    Flume 自定义 组件
    Source r1 has been removed due to an error during configuration java.lang.IllegalArgumentException: Required parameter bind must exist and may not be null & 端口无法连接
  • 原文地址:https://www.cnblogs.com/sry622/p/10834693.html
Copyright © 2011-2022 走看看