“序列”与java中的“流”不知道有什么关系,也不知道是否可以理解为一长串计算机硬件基本单位排列的“长长队伍”,用于存储或是用计算机网络中的数据以各种各样,繁杂但是有结构的协议封装,
加密,转发······
但是python中为什么要用json模块呢?先不管
json模块
json.dumps()与json.loads()
先进行序列化的第一步,将python中的变量(此时使用字典,在内存中)转化为字符串
import json
dic = {"name": "CHJ", "name2": "chj"}
Jstr_dic = json.dumps(dic)
str_dic = str(dic)
比较两个字符串(注释为输出)
print(type(eval(Jstr_dic))) # <class 'dict'>
print(type(eval(str_dic))) # <class 'dict'>
print(dic, type(dic)) # {'name': 'CHJ'} <class 'dict'>
print(Jstr_dic, type(Jstr_dic)) # {"name": "CHJ"} <class 'str'>
单引号与双引号在python中一对使用好像是没区别的
但是为什么会这样?完全不知道
懒得说一堆了,分别将两串字符串写入两个文件,每个文件都已两种方式读出来
(注释为结果)
with open(file="test1.txt", mode="w", encoding="utf-8") as f1:
f1.write(Jstr_dic)
f1.close()
with open(file="test2.txt", mode="w", encoding="utf-8") as f2:
f2.write(str_dic)
f2.close()
with open(file="test1.txt", mode="r", encoding="utf-8") as f1:
r1 = f1.read()
r1_2 = json.loads(r1)
print(r1, type(r1))
print(r1_2, type(r1_2))
f1.close()
# {"name": "CHJ", "name2": "chj"} <class 'str'>
# {'name': 'CHJ', 'name2': 'chj'} <class 'dict'>
with open(file="test2.txt", mode="r", encoding="utf-8") as f2:
r2 = f2.read()
r2_2 = json.loads(r1)
print(r2, type(r2))
print(r2_2, type(r2_2))
f2.close()
# {'name': 'CHJ', 'name2': 'chj'} <class 'str'>
# {'name': 'CHJ', 'name2': 'chj'} <class 'dict'>
这就搞不懂了,既然都可以用json.loads()将序列转为字符串再转为python对象读出来(并可以用python特有的数据处理方法对数据进行操作),那么用json.dumps将对象转换为json字符串的目的是什么呢?还是不懂。估计就不是用于文件的写操作,而是用于传输之类的用途。
json.dump()与json.load()
就是json.dumps()与json.loads()的简化版,用于直接保存读取文件,而不是对数据进行python中的操作。懒得敲了,莫得代码演示
pickle模块
同上,在于数据与序列的中间过程是二进制序列即bytes类型,而不是string类型。“由于要考虑到多语言的兼容性问题,json 模块并不支持Python除基本数据类型之外的类型。如:set类型,函数类型,类等 等。但是pickle由于只支持Python使用,所以有了更强的对Python序列化对象的支 持。pickle可以序列化函数,类等等,但是并不推荐这么做,因为保存的只有一个内 存地址。另外,由于pickle的局限性太强所以更推荐使用json进行序列化操作。”
代码同上,但在读写代码上mode(模式)要加一个b(二进制)参数,无需使用UTF-8编码。
with open(file="test",mode="wb") as f:
第一遍博客马马虎虎,写完人昏昏沉沉,写完发现好像这点p东西都没必要写