JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

       json & pickle & shelve 模块

# json序列化
import json,time
user={'name':'egon','age':18,'nb':True}
with open('user.json','w',encoding='utf-8') as f:
    f.write(json.dumps(user)) # dumps

students=['alex','egon','wxx','yxx']
json.dump(students,open('students.json','w',encoding='utf-8')) # dump

dic1 = {'type':'dic1','username':'loleina','age':16}
dump
True,则会跳过这类key

# pickle序列化
import pickle
s={1,2,3}
with open('s.pkl','wb') as f:
    f.write(pickle.dumps(s)) # dumps

pickle.dump(s,open('s.pkl','wb'))  # dump

#json反序列化
import json
with open('user.json','r',encoding='utf-8') as f:
    user=json.loads(f.read()) #json.loads
    print(user['name'])
user=json.load(open('user.json','r',encoding='utf-8')) #json.load
print(user['age'])

#pickle反序列化
import pickle
with open('s.pkl','rb') as f:
    s=pickle.loads(f.read()) #loads
    print(s,type(s))
s=pickle.load(open('s.pkl','rb')) #load
print(s, type(s))

 

 shelve 模块

     shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

import shelve

f=shelve.open('db.shl')
# f['stu1']={'name':'alex1','age':38}
# f['stu2']={'name':'alex2','age':28}
print(f['stu1']['name'])
f.close()

 

相关文章:

  • 2021-09-19
  • 2018-10-18
  • 2021-11-04
  • 2021-07-21
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-20
  • 2021-11-14
  • 2021-07-09
  • 2021-11-07
  • 2021-07-19
  • 2022-12-23
相关资源
相似解决方案