day04_03 序列化与反序列化

test.text

{"name": "alex", "age": 22}{"name": "alex", "age": 21}

json序列化1.py

__author__ = "Alex Li"


#处理简单数据
import json
info = {
    'name':'alex',
    'age':22,
}

f = open("test.text","w")
print(json.dumps(info))
f.write( json.dumps(info))
f.close()


# import pickle
#
# def sayhi(name):
#     print("hello,",name)
#
# info = {
#     'name':'alex',
#     'age':22,
#     'func':sayhi
# }
#
# f = open("test.text","wb")
# f.write( pickle.dumps(info))
# f.close()

json反序列化1.py

__author__ = "Alex Li"


#处理简单数据
import json
f = open("test.text","r")

data = json.loads(f.read())
print(data["age"])
f.close()


# import pickle
#
# def sayhi(name):
#     print("hello,", name)
#     print("hello2,",name)
#
# f = open("test.text","rb")
#
# data = pickle.loads(f.read())
# data["func"]("Alex")
# print(data["name"])
# print(data["age"])
# f.close()

json序列化2.py

__author__ = "Alex Li"

import pickle

def sayhi(name):
    print("hello,",name)

info = {
    'name':'alex',
    'age':22,
    'func':sayhi
}

f = open("test.text","wb")
pickle.dump(info,f) #f.write( pickle.dumps( info) )
f.close()

json反序列化2.py

__author__ = "Alex Li"
import pickle

def sayhi(name):
    print("hello2,",name)

f = open("test.text","rb")

data = pickle.load(f) #data = pickle.loads(f.read())
data["func"]("Alex")
print(data["name"])
print(data["age"])
f.close()

json序列化3.py

__author__ = "Alex Li"

import json

def sayhi(name):
    print("hello,",name)

info = {
    'name':'alex',
    'age':22,
}

f = open("test.text","w")
f.write( json.dumps( info) )

info['age'] = 21
f.write( json.dumps( info) )

f.close()

json反序列化3.py

__author__ = "Alex Li"

import json

f = open("test.text","r")

for line in f:
    print(json.loads(line))     #只能dump一次

posted @ 2021-06-06 01:21  flytoyou  阅读(33)  评论(0编辑  收藏  举报