Python——序列化模块

#json 模式

1、dumps、loads  方法 针对内存

dic = {'k1':'v1'}
#转换成json
import json
str_d = json.dumps(dic) #序列化
dic_d = json.loads(str_d)#反序列化
#可序列化的类型 数字 字符串 列表 字典 

2、dump 、load 方法  针对文件

dic = {1:'a',2:'b'}
f = open('fff','w',encoding = 'utf-8')
json.dump(dic,f,ensure_ascii=False) #序列化 按照正常的编码格式,显示中文
f.close()
f = open('fff','w',encoding = 'utf-8')
ret = json.load() #反序列化
print(type(res),res)
f.close()

#pickle模式

#可以分布的 dump load 操作文件需要使用 'wb' 模式
import pickle
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic)  #一串二进制内容

dic2 = pickle.loads(str_dic)
print(dic2)    #字典

import time
struct_time1  = time.localtime(1000000000)
struct_time2  = time.localtime(2000000000)
f = open('pickle_file','wb')
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close()

#shelve

open方法

import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()
import shelve
f1 = shelve.open('shelve_file')
existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing)

import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
print(existing)

f.close()

f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2)

import shelve
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()

f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f2['key']['new_value'] = 'this was not here before'
f2.close()
posted @ 2018-10-07 21:34  澄心元素  阅读(222)  评论(0编辑  收藏  举报