Python 3.x--序列化及反序列化


1、JSON序列化

import json

#將字典寫入文件,JSON序列化(dumps)
a = {
'name':'lili',
'age':22,
'salary':2000
}

with open('file01.txt','w') as f:
f.write(json.dumps(a))

2、JSON反序列化

#將文件讀出,並顯示為字典,JSON反序列化(loads)

with open('file01.txt','r') as f1:
line = json.loads(f1.read())
print(line['age'])

3、Pickle序列化

------dumps方法------

import pickle

def func1(name):
print('hello',name)

a = {
'name':'lili',
'age':22,
'salary':2000,
'arge':func1
}

with open('file01.txt','wb') as f:
f.write(pickle.dumps(a))

------dump方法------

 

import pickle

def func1(name):
print('hello..',name)

a = {
'name':'lili',
'age':22,
'salary':2000,
'arge':func1
}

with open('file01.txt','wb') as f:
pickle.dump(a,f)

 

4、Pickle反序列化

------loads方法------

with open('file01.txt','rb') as f1:
def func1(name):
print('hello', name)
line = pickle.loads(f1.read())
print(line['arge']('lili'))

運行結果:

 

------load方法------

with open('file01.txt','rb') as f1:
data = pickle.load(f1)
print(data)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM