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

    一、json模块中的dumps()方法和loads()方法

    json 在所有的语言之间都通用 : json序列化的数据 在python上序列化了 那在java中也可以反序列化。

    几种python数据的序列化

     1 # 问题1
     2 # dic = {1 : 'value',2 : 'value2'}
     3 # ret = json.dumps(dic)  # 序列化
     4 # print(dic,type(dic))   
     5 # print(ret,type(ret))   # {"age": 100, "2": "value2"} <class 'str'>
     6 #
     7 # res = json.loads(ret) # 反序列化
     8 # print(res,type(res))
     9 
    10 # 问题2
    11 # dic = {1 : [1,2,3],2 : (4,5,'aa')}
    12 # ret = json.dumps(dic)  # 序列化
    13 # print(dic,type(dic))
    14 # print(ret,type(ret))   {"1": [1, 2, 3], "2": [4, 5, "aa"]} <class 'str'>
    15 
    16 # res = json.loads(ret) # 反序列化
    17 # print(res,type(res))
    18 
    19 # 问题3
    20 # s = {1,2,'aaa'}
    21 # json.dumps(s)  #  TypeError: Object of type 'set' is not JSON serializable
    22 
    23 # 问题4 # TypeError: keys must be a string
    24 # json.dumps({(1,2,3):123})
    View Code

    能够处理的数据类型是非常有限的 : 字符串 列表 字典 数字。

    字典中的key只能是字符串。

    1、字典转换为字符串,在由字符串转换为字典

    1 dic = {'key' : 'value','key2' : 'value2'}
    2 import json
    3 ret = json.dumps(dic)  # 序列化
    4 print(dic,type(dic))
    5 print(ret,type(ret))
    6 
    7 res = json.loads(ret) # 反序列化
    8 print(res,type(res))

    2、字典的Key必须是字符串,若不是python自动转换

    dic = {1 : 'value',2 : 'value2'}
    ret = json.dumps(dic)  # 序列化
    print(dic,type(dic))
    print(ret,type(ret))
    
    res = json.loads(ret) # 反序列化
    print(res,type(res))

    最终字典key是字符串

    3、字典的value如果是元组,最终反序列化后value转换为列表

    dic = {1 : [1,2,3],2 : (4,5,'aa')}
    ret = json.dumps(dic)  # 序列化
    print(dic,type(dic))
    print(ret,type(ret))

    4、向文件中记录字典

    1 import json
    2 dic = {'key' : 'value','key2' : 'value2'}
    3 ret = json.dumps(dic)  # 序列化
    4 with open('json_file','a') as f:
    5      f.write(ret)

    5、从文件中读取字典

    1 with open('json_file','r') as f:
    2      str_dic = f.read()
    3 dic = json.loads(str_dic)
    4 print(dic.keys())

     

    二、json模块中的dump()和load()方法

    1、dump()和load()是直接操作文件的

    1 dic = {'key1' : 'value1','key2' : 'value2'}
    2 with open('json_file','a') as f:
    3      json.dump(dic,f)
    4 
    5 with open('json_file','r') as f:
    6      dic = json.load(f)
    7 print(dic.keys())

     2、连续的放和取文件

     1 with open('json_file','a') as f:
     2      str_dic = json.dumps(dic)
     3      f.write(str_dic+'
    ')
     4      str_dic = json.dumps(dic)
     5      f.write(str_dic + '
    ')
     6      str_dic = json.dumps(dic)
     7      f.write(str_dic + '
    ')
     8 
     9 with open('json_file','r') as f:
    10      for line in f:
    11          dic = json.loads(line.strip())
    12          print(dic.keys())

     3、关于dumps()中的参数

    1 import json
    2 data = {'username':['李华','二愣子'],'sex':'male','age':16}
    3 json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'),ensure_ascii=False)
    4  print(json_dic2)

    根据参数可以将字典转换为标准的格式。

    sort_keys=True根据字典的Key排序
    separators=(',',':')  表示字典的格式

    ensure_ascii=False 处理汉字乱码

     三、pickle模块

    1.支持在python 中的几乎所有的数据类型

    2.dumps 序列化的结果只能是字节

    3.只能在python中使用
    4.在和文件操作的时候,需要用rb wb的模式打开文件
    5.可以多次dump 和 多次load

    1 import pickle
    2 dic = {(1,2,3):{'a','b'},1:'abc'}
    3 
    4 ret = pickle.dumps(dic)
    5 print(ret)

    读、写文件

     1 dic = {(1,2,3):{'a','b'},1:'abc'}
     2 dic1 = {(1,2,3):{'a','b'},2:'abc'}
     3 dic2 = {(1,2,3):{'a','b'},3:'abc'}
     4 dic3 = {(1,2,3):{'a','b'},4:'abc'}
     5 with open('pickle_file','wb') as f:
     6      pickle.dump(dic, f)
     7      pickle.dump(dic1, f)
     8      pickle.dump(dic2, f)
     9      pickle.dump(dic3, f)
    10 
    11 with open('pickle_file','rb') as f:
    12      ret = pickle.load(f)
    13      print(ret,type(ret))
    14      ret = pickle.load(f)
    15      print(ret,type(ret))
    16      ret = pickle.load(f)
    17      print(ret, type(ret))
    18      ret = pickle.load(f)
    19      print(ret, type(ret))
    20      ret = pickle.load(f)
    21      print(ret, type(ret))

     在读文件时 当读到最后一个文件时系统会报错:EOFError: Ran out of input

    异常处理:当读到最后一个文件时自动停止

    1 with open('pickle_file','rb') as f:
    2     while True:
    3         try:
    4             ret = pickle.load(f)
    5             print(ret,type(ret))
    6         except EOFError:
    7             break

    三、pickle模块

     1 import pickle
     2 
     3 class Person:
     4     def __init__(self, name, age):
     5         self.name = name
     6         self.age = age
     7 
     8     def chi(self):
     9         print(self.name, "吃东西")
    10 
    11 
    12 p = Person("Andey", 40)
    13 
    14 bs = pickle.dumps(p) # 把对象拍散
    15 # 写入文件
    16 pickle.dump(p, open("person.dat", mode="wb"))
    17 print(bs)
    18 
    19 pp = pickle.loads(bs) # 组装
    20 # 读取文件
    21 pp = pickle.load(open("person.dat", mode="rb"))
    22 pp.chi()
  • 相关阅读:
    sw
    ++1
    test
    为了
    发送邮件
    新建121212
    29012
    pthread_create/join函数
    recv函数学习
    socketpair用法学习
  • 原文地址:https://www.cnblogs.com/liaopeng123/p/9511746.html
Copyright © 2011-2022 走看看