标签:图片 数据 Shelve模块 打开 键值对 字节 必须 字典 json模块
我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,python中叫pickling
序列化之后就可以把序列化后的内容写入磁盘或通过网络传输到别的机器上
反序列化:unpickling,也就是loads的过程
import json dic = {"name": "alex"} data = json.dumps(dic) print(data, type(data))
经json处理,就把别的数据类型变为json字符串
json规范的字符串必须使用双引号
处理过程:dic = {‘name’: ‘alex‘}----> {"name": "alex"} ----> ‘{"name": "alex"}‘ (先把所有单引号变为双引号,再在外面加上单引号)
i = 8 #----> ‘8‘
s = ‘hello‘ ----->"hello"----->‘ "hello" ‘
import json dic = {"name": "alex"} data = json.dumps(dic) with open("json_txt", "w") as f: f.write(data)
import json dic = {"name": "alex"} # data = json.dumps(dic) with open("json2_txt", "w") as f: json.dump(dic, f)
import json with open("json_txt","r")as f_read: data = f_read.read() data = json.loads(data) print(type(data)) print(data["name"])
import json with open("json_txt","r")as f_read: # data = f_read.read() data = json.load(f_read) print(type(data)) print(data["name"])
和 json 的功能、方法一样,
区别:pickle是把数据处理成字节, 且支持的数据类型更多,例如: 类,函数...
写入的文件,直接打开是看不懂的
import pickle dic = {"name": "alex", "age":18} with open("pickle_test", "wb") as f: dic_str = pickle.dumps(dic) f.write(dic_str)
import pickle with open("pickle_test", "rb") as f: data = f.read() data = pickle.loads(data) print(data["age"])
import shelve f = shelve.open("shelve_test") f["name"] = "alex" #将一个键值对写入文件 f["stu1"] = {"name":"alvin", "age":18} #将一个键值对写入文件 print(f.get("name")) print(f.get("stu1")["age"])
python课堂整理26 ---json、pickle、shelve模块(序列化处理)
标签:图片 数据 Shelve模块 打开 键值对 字节 必须 字典 json模块
原文地址:https://www.cnblogs.com/dabai123/p/11334347.html