zoukankan      html  css  js  c++  java
  • Python—序列化和反序列化模块(json、pickle和shelve)

    什么是序列化

    • 我们把对象(或者变量)从内存中变为可存储或者可传输的过程称为序列化。在python中为pickling,在其他语言中也被称之为serialization,marshalling,flattening等等。
    • 即序列化之后就可以将内存中的程序内容写入硬盘或者通过网络传输到其他机器上去。
    • 反序列化的过程则相反:将硬盘中的内容变为可以在内存中运行的程序的过程称为反序列化。

    Json模块

    # encoding:utf-8
    # 通过序列化和反序列化将内容存储到文件,在读取文件内容。
    import json
    jsonDict = {"name": "张三", "age": 26}
    
    # json encode ---> json编码(将python对象转换成json对象)。dict --> json str。dumps --> 序列化
    jsonDumps = json.dumps(jsonDict)  
    print jsonDumps, type(jsonDumps)  # 结果:{"age": 26, "name": "u5f20u4e09"}  <type 'str'>
    with open("information.txt", "w") as fw:
        fw.write(jsonDumps)
    
    # json decode ---> json解码(将json对象转换成python对象)。json str --> dict。loads --> 反序列化
    with open("information.txt", "r") as fr:
        jsonDumps = fr.read()         
    jsonLoads = json.loads(jsonDumps)
    print jsonLoads, type(jsonLoads)  # 结果:{u'age': 26, u'name': u'u5f20u4e09'}  <type 'dict'>
    import json
    jsonDict = {"name": "张三", "age": 26}
    
    with open(
    "information.txt", "w") as fw: json.dump(jsonDict, fw) # 相当于:1、jsonDumps=json.dumps(jsonDict) 2、fw.write(jsonDumps) with open("information.txt", "r") as fr: jsonDict = json.load(fr) # 相当于:info_dic =json.loads(fr.read()) print jsonDict, type(jsonDict) # 结果:{u'age': 26, u'name': u'u5f20u4e09'} <type 'dict'>
  • 相关阅读:
    Hql语句注意事项总结
    数据库主键设计之思考
    UTF8的中文问题
    DirectShow SDK笔记【关于DirectShow(4)】
    关于kindeditor上传图片出现"服务器发生故障"的解决办法
    php 分隔字符串为数组
    yum 一次性安装 apache mysql php
    linux下安装gd库
    三种实现PHP伪静态页面的方法
    (转)Linux利器 strace
  • 原文地址:https://www.cnblogs.com/liuhaidon/p/11670755.html
Copyright © 2011-2022 走看看