您好,登錄后才能下訂單哦!
json序列化
info = {
'name':'alex',
'age':22
}
f = open("test.txt",'w')
f.write(str(info)) #把一個字典轉(zhuǎn)換成字符串 從內(nèi)存存到硬盤的過程叫序列化
f.close()
import json
info = {
'name':'alex',
'age':22
}
f = open("test.txt",'w')
#print(json.dumps(info))
f.write(json.dumps(info)) #把一個字典轉(zhuǎn)換成字符串 從內(nèi)存存到硬盤的過程叫序列化
f.close() #序列化dumps 函數(shù)不可以序列化 只能處理簡單的跨平臺數(shù)據(jù)交互
import json
info = {
'name':'alex',
'age':22
}
f = open("test.txt","w")
json.dump(info,f)
info["age"]=21
json.dump(info,f) #一般只dump一次,因為3.x版本只能load一次,dump多次沒意義
f.close()
json反序列化
f = open("test.txt",'r')
data = eval(f.read())
f.close()
print(data['age'])
import json
f = open("test.txt",'r')
data = json.loads(f.read()) #反序列化loads
print(data['age'])
import json
f = open("test.txt",'r')
#data = json.load(f) #等于data= json.loads(f.read()) 會報錯 3.X只能load一次
for line in f:
print(line)
pickle序列化
import pickle
def sayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.txt",'wb')
#print(pickle.dumps(info))
f.write(pickle.dumps(info)) #pickle可以序列化所有的數(shù)據(jù)
f.close()
import pickle
def sayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.txt","wb")
pickle.dump(info,f) # 等于f.write(pickle.dumps(info))
#pickle.dump(對象,文件)
f.close()
pickle反序列化
import pickle
def sayhi(name):
print("hello2,",name)
f = open("test.txt",'rb')
data = pickle.loads(f.read()) #反序列化loads pickle只能用在python里面,java不認
print(data["func"]("alex")) #反序列化只要函數(shù)名一樣就可以,序列化的是整個的數(shù)據(jù)對象
import pickle
def sayhi(name):
print("hello2,",name)
f=open("test.txt",'rb')
data = pickle.load(f) #等于data= pickle.loads(f.read())
print(data["func"]("alex"))
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。