python基础--json,pickle和shelve模块

一.JSON &pickle

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换  字符串必须是双引号,不能是单引号
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、dump

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

dumps,loads处理字符串

dump,dump写入文件

pickle处理特有的,比如函数;json和pickle读文件只能处理只有一行的文件数据,所以基本用json和pickle读写只处理一次。要处理多次使用shelve模块

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

import json
import pickle

data={"name":"shisanjun","age":23} # 字典
data_json=json.dumps(data)#转成字符串

print(data_json)
print(type(data_json))

data1=json.loads(data_json) #转成字典
print(data1)

print(type(data1))

with open("json.txt",'w',encoding="utf-8") as f:
    json.dump(data,f)
    json.dump(data1,f)

# with open("json.txt",'r',encoding="utf-8") as f:
#     print(json.load(f)) #报错 Extra data: line 1 column,load只能读文件一行,而现在文件中有两行

def func():
    print("test func")

data2={"name":"shisanjun","age":23,"func":func}
# with open("json1.txt",'w',encoding="utf-8") as f:
#     json.dump(data2,f) #报错TypeError: Object of type 'function' is not JSON serializable,json只能处理简单类型
print(type(data2))
with open("json2.txt",'wb') as f: #必须byte方式写
    pickle.dump(data2,f)

with open("json2.txt",'rb') as f1:

    pickle.load(f1)["func"]()

二.shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

import shelve

d=shelve.open('shelve.txt')#打开文件

def test1():
    print("shelve deal function")

name=["alex","rain","test"]
d["test"]=name#持久化列表
d["t1"]=test1 ##持久化类
d.close()

 

posted on 2017-05-14 09:28  shisanjun  阅读(240)  评论(0)    收藏  举报

导航