码迷,mamicode.com
首页 > 编程语言 > 详细

python之路-14.Json & pickle 数据序列化

时间:2017-11-26 14:57:15      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:.json   序列化   lin   恢复   函数   read   load   就是   info   

14.1序列化

示例1

#!Author:lanhan
#把字典的内存数据类型通过字符串存到硬盘上(json.dumps),仅处理字符串、列表、字典等
import json
info = {
    ‘name‘:‘lanhan‘,
    ‘age‘:22
}
f = open("test.txt","w")
print(json.dumps(info))
f.write(json.dumps(info))
f.close()

 

示例2:   pickle可处理复杂的,如函数等

import pickle
def sayhi(name):
    print("hello",name)
info = {
    ‘name‘:‘lanhan‘,
    ‘age‘:22,
    ‘func‘:sayhi
}
f = open("test.txt","wb")
f.write(pickle.dumps(info))

 

示例3

import json
def sayhi(name):
    print("hello",name)
info = {
    ‘name‘:‘lanhan‘,
    ‘age‘:22
}
f = open("test.txt","w")
f.write(json.dumps(info))
info[‘age‘] = 21
f.write(json.dumps(info))
f.close()

 

14.2反序列化

示例1

#!Author:lanhan
#把硬盘的数据类型恢复到内存中(json.loads),仅处理字符串、列表、字典等
import json
f = open("test.txt","r")
data = json.loads(f.read())
f.close()
print(data["age"])

 

示例2pickle可处理复杂的,如函数等

##pickle

import pickle
def sayhi(name):
    print("hello",name)
    print("hello2",name)
f = open("test.txt","rb")
data = pickle.load(f)      ###====#data = pickle.loads(f.read())

print(data["func"]("lanhan"))

 

示例3

#!Author:lanhan
#c错误的,说明有多个状态能够多次dump,不能多次loads,也就是说有多个状态时就dump多个文件,dump一次,就load一次
import json
f = open("test.txt","r")
for line in f:
    print(json.loads(line))
print(data)

python之路-14.Json & pickle 数据序列化

标签:.json   序列化   lin   恢复   函数   read   load   就是   info   

原文地址:http://www.cnblogs.com/decorator/p/7898879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!