zoukankan      html  css  js  c++  java
  • 序列化模块

    序列化模块

    • 什么叫序列化
      • 原本的字典、列表等内容转换成一个字符串的过程就叫做__序列化__
      • 初级认为:数据类型-->字符串
    • 序列化的目的
      1. 储存:以某种存储形式使自定义对象持久化;
      2. 传输:将对象从一个地方传递到另一个地方。
      3. 维护:使程序更具维护性。
    • 反序列化
      • 字符串-->其他数据类型

    01. json模块 -很重要

    • 通用的序列化格式
      • 通用:适用于各种编程语言
      • 兼容:只有很少的数据类型能够通过json转换
        • 列表
        • 字典
        • 元组
        • 字符串
        • 数字

    直接操作内存中的数据类型

    • json.dumps()序列化

    • jsom.loads()反序列化

        import json
        dic = {'k1': 'v1'}
        str_d = json.dumps(dic) #序列化
        print(type(str_d), str_d)
        #结果				
        <class 'str'> {"k1": "v1"}
        str_d = json.load(str_d) #反序列化
        print(type(str_d), str_d)
        #结果
        <class 'dict'> {'k1': 'v1'}
      

    和文件相关的方法

    • json.dump()向文件里写
      • 一次性写进去

        import json
        dic = {'k1':'v1'}
        f = open('file.txt', 'w', encoding='utf-8')
        json.dump(dic, f) #先将字典序列化后写入文件
        f.close()

    • json.load()向文件外读取
      • 一次性读出来

        import json
        f = open('file.txt', encoding='utf-8')
        dic = json.load(f)
        f.close()

    • 中文情况
      • json.dump(dic, f, ensure_ascii=False)
      • ensure_ascii=False可以防止中文字符写入文件编程bytes类型数据

    分步向文件写入

    import json
    list = [{'k1':v1}, {'k2':v2}, {'k3':v3}]
    for i in list:
    	f = open('file', 'w', encoding='utf-8')
    	f.write(json.dumps(i) + '
    ')
    f.close()
    

    分步从文件中读取

    import	json
    f = open('file')
    for line in f:
    	print(json.loads(line.strip()))
    

    02. pickle模块 -重要

    • 广泛:所有的python数据类型都能转换
    • 限制:所有序列化的数据也只有python能解析
    • 用法同json,用法一模一样
    • 序列化之后是bytes数据类型
      • dump()load()需要文件采用wb或者rb才能操作文件
    • 可以分步dump()load()
      • 分步写入必须分步读取

      • 先写先读

          import pickle
          l1 = ['1', '2']
          l2 = ['a', 'b']
          #写入
          f = open('file', 'wb', encoding='utf-8')
          pickle.dump(l1, f)	#第一个数据导入
          pickle.dump(l2, f)	#第二个数据导入
          f.close()
          #读取
          f = open('file', 'rb', encoding='utf-8')
          l1 = pickle.load(f)	#读取第一个数据
          l2 = pickle.load(f) #读取第二个数据
          f.close()
        

    03. shelve模块 -一般

    • 只有一个shelve.open()方法,要结合.close()使用

        #导入shelve模块
        import shelve
        #写入数据
        f = shelve.open('file', flag='w') 	#打开文件,没有自动创建
        f['name'] = '李王' #指定f[key]直接赋值数据就行
        f.close()	#关闭文件句柄
        #读取数据
        f = shelve.open('file', flag='r') #打开文件,没有自动创建
        shelve_name = f['name']	 #指定f[key]直接读取数据就行
        print(shelve_name)#打印结果
        f.close()	#关闭句柄
      
    • writeback=True参数,修改已经写入的数据时需要加入,要不然无法感知文件修改

        #不写入参数
        import shelve
        f = shelve.open('file', flag='w')	#没有添加writeback参数
        f['key'] = {}
        f['key']['new_key'] = 'new_str'
        f.close()
        #读取
        f = shelve.open('file', flaf='r')
        print(f['key']['new_key'])
        #结果
        {}
        KeyError: 'new_key' #提示找不到'new_key',说明没有写入新数据
        
        #写入参数
        import shelve
        f = shelve.open('file', flag='w', writeback=True)	#添加writeback参数
        f['key'] = {}
        f['key']['new_key'] = 'new_str'
        f.close()
        #读取
        f = shelve.open('file', flag='r')
        print(f['key'])
        print(f['key']['new_key'])
        f.close()
        #结果
        {'new_key': 'new_str'}
        new_str
  • 相关阅读:
    225. Implement Stack using Queues
    232. Implement Queue using Stacks
    LeetCode 763 划分字母区间
    CentOS7+eDEX-UI打造属于你的极客桌面
    好玩又有趣的linux终端命令
    Linux 应急响应入门——入侵排查
    active_anon/inactive_anon
    Red Hat 平台的推荐交换大小是多少?
    为什么RHEL系统使用交换空间而不是释放缓存和缓冲内存?
    RHEL 交换内存(Swap)使用率为 100%
  • 原文地址:https://www.cnblogs.com/liliudong/p/9593973.html
Copyright © 2011-2022 走看看