标签:序列化 eval bsp name pre print 序列 使用 def
info = {
"name":"roger",
"age":12
}
f = open("test.txt","w")
f.write(str(info))
f.close()
f = open("test.txt","r")
data = f.read()
print(data["name"])
f.close()
会报错
使用eval()
f = open("test.txt","r")
data = f.read()
print(eval(data)["name"])
f.close()
用json的方式
import json
info = {‘name‘:‘roger‘,‘age‘:12}
print(json.dumps(info))
f = open("test.txt","w")
f.write(json.dumps(info))
import json
f = open("test.txt","r")
data = json.loads(f.read())
print(data["age"])
f.close()
再来一例子:pic
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
print(pickle.dumps(info))
f = open("test.txt","wb")
f.write(pickle.dumps(info))
import pickle
def functest():
pass
f = open("test.txt","rb")
data = pickle.loads(f.read())
print(data["age"])
f.close()
再来一例子
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
print(pickle.dumps(info))
f = open("test.txt","wb")
f.write(pickle.dumps(info))
import pickle
def functest():
print("test")
f = open("test.txt","rb")
data = pickle.loads(f.read())
print(data["func"]())
f.close()
上面的也可以这写:
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
f = open("test.txt","wb")
pickle.dump(info,f)
f.close()
import pickle
def functest():
print("test")
f = open("test.txt","rb")
data = pickle.load(f)
print(data["func"]())
f.close()
记住:dump一次,load一次。
标签:序列化 eval bsp name pre print 序列 使用 def
原文地址:https://www.cnblogs.com/wherewhenwho/p/9035335.html