python之json&pickle

时间:2021-06-05 08:59:56

用于序列化的两个模块:

json:用于字符串和python数类型间进行转换

oickle:用于python特有的类型和python的数据类型间进行转换

json、pickle模块提供四个功能:dumps、dump、loads、load

python之json&pickle

使用json&pickle将转化成字符串写入文件

 import json
import pickle def sayhi(name):
print("hello,", name) info = {
"name":"guoxf",
"age":"",
"sex":"nan",
"func":sayhi
} info1 = {
"name":"guoxf",
"age":"",
"sex":"nan",
# "func":sayhi
} f = open("a.txt", "wb")
# json.dump(info1) # 两者完全相等 json.dumps(info1)
pickle.dump(info, f) # 两者完全相等 f.write(pickle.dumps(info))
f.close()

使用json&pickle将文件中的字符串转化成字典读取

 import json
import pickle def sayhi(name):
print("hello,", name) f = open("a.txt", "rb")
# data = json.loads(f.read())
# data = pickle.loads(f.read())
data = pickle.load(f)
print(data) f.close() print(data["func"]("gxf"))