序列化模块— json模块,pickle模块,shelve模块
序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化。
# 序列化模块
# 数据类型转化成字符串的过程就是序列化
# 为了方便存储和网络传输
# json
# dumps
# loads
# dump 和文件有关
# load load不能load多次 # import json
# data = {'username':['李华','二愣子'],'sex':'male','age':16}
# json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'),ensure_ascii=False)
# print(json_dic2) # pickle
#方法和json一样
#dump和load的时候 文件是rb或者wb打开的
#支持python所有的数据类型
#序列化和反序列化需要相同的环境
# shelve
# open方法
# open方法获取了一个文件句柄
# 操作和字典类似
先来个总结
json模块
json特点:
1.只能处理简单的可序列化的对象:
json 可以序列化的类型有 数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)
2.json支持不同语言之间的数据交互
json提供了四个方法:dumps,loads 和 dump,load
import json
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = json.dumps(dic) #序列化:将一个字典转换成一个字符串
print(type(str_dic),str_dic) #<class 'str'> {"k3": "v3", "k1": "v1", "k2": "v2"}
#注意,json转换完的字符串类型的字典中的字符串是由""表示的 dic2 = json.loads(str_dic) #反序列化:将一个字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(type(dic2),dic2) #<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic = json.dumps(list_dic) #也可以处理嵌套的数据类型
print(type(str_dic),str_dic) #<class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
list_dic2 = json.loads(str_dic)
print(type(list_dic2),list_dic2) #<class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
dumps和loads
import json
f = open('json_file','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f) #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close() f = open('json_file')
dic2 = json.load(f) #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)
dump和load
#json不支持多次载入再出,如果需要,用以下这个思路
#dumps和loads多行
l = [{'k1':''},{'k2':''},{'k3':''}]
f = open('duohang','w')
for i in l:
f.write(json.dumps(i)+'\n')
f.close()
json中dumps多行
import json
#pickle可以序列化python任何数据类型,比如集合
#json 可以序列化的类型有 数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)
info = {
'name':'郭坤祥',
'age':19,
'job':'IT'
}
with open('序列化.txt','w',encoding='utf-8') as f:
#f.write(json.dumps(info)) #整句话等价于 json.dump(info,f)
json.dump(info,f,ensure_ascii=False) #要写dump的时候文件里显示中文,需要加 ensure_ascii=False 这个参数 with open('序列化.txt','r',encoding='utf-8') as f2:
# ret = json.loads(f2.read()) #整句话等价于 print(json.load(f2))
# print(type(ret),ret)
print(json.load(f2)) dumps和loads是在内存中操作数据,dump和load必须要有文件才可以使用
文件中的这四个方法
import json
f = open('file','w')
json.dump({'国籍':'中国'},f)
ret = json.dumps({'国籍':'中国'})
f.write(ret+'\n')
json.dump({'国籍':'美国'},f,ensure_ascii=False)
ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
f.write(ret+'\n')
f.close()
ensure_asci
Serialize obj to a JSON formatted str.(字符串表示的json对象)
Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。)
If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
sort_keys:将数据根据keys的值进行排序。
To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
其他参数说明
import json
data = {'username':['李华','二愣子'],'sex':'male','age':16}
json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
print(json_dic2)
json格式化输出
#json一次不能读取多行,f.write(json.dumps(info)+'\n')
pickle模块
pickle和json用法一样,也提供 dumps,loads,dump,load 四个方法
但是pickle在dumps的时候,是把数据存为bytes数据类型
所以pickle在使用文件的时候用到的模式就是 wb和rb
pickle可以序列化python任何数据类型,比如集合
json 可以序列化的类型有 数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)
pickle可以分步dump和分布load json就不行了
#pickle 分步序列
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic) #一串二进制内容 dic2 = pickle.loads(str_dic)
print(dic2) #字典 import time
struct_time1 = time.localtime(1000000000)
struct_time2 = time.localtime(2000000000)
f = open('pickle_file','wb')
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close()
pickle 分步序列
shelve模块
shelve模块是python3中新增的序列化模块,平常pickle和json已经足以应付日常需求,故shelve比较少使用。
简单用法如下:
import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据
f.close() import shelve
f1 = shelve.open('shelve_file')
existing = f1['key'] #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing) 注意shelve有个坑,在虽然开启了只读模式,但是还是会更改对应的值
import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
####### f['key'] = 50 #坑在这里
print(existing) f.close() f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2) import shelve
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close() f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
# f2['key']['new_value'] = 'this was not here before'
f2.close()
序列化模块— json模块,pickle模块,shelve模块的更多相关文章
- 【转】Python之数据序列化(json、pickle、shelve)
[转]Python之数据序列化(json.pickle.shelve) 本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型 ...
- python常见模块之序列化(json与pickle以及shelve)
什么是序列化? 我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flatte ...
- 20,序列化模块 json,pickle,shelve
序列化模块 什么叫序列化? 将原本的字典,列表等内容转换成一个字符串的过程叫做序列化. 序列化的目的? 数据结构 通过序列化 转成 str. str 通过反序列化 转化成数据结构. json: jso ...
- Python—序列化和反序列化模块(json、pickle和shelve)
什么是序列化 我们把对象(或者变量)从内存中变为可存储或者可传输的过程称为序列化.在python中为pickling,在其他语言中也被称之为serialization,marshalling,flat ...
- os常用模块,json,pickle,shelve模块,正则表达式(实现运算符分离),logging模块,配置模块,路径叠加,哈希算法
一.os常用模块 显示当前工作目录 print(os.getcwd()) 返回上一层目录 os.chdir("..") 创建文件包 os.makedirs('python2/bin ...
- python模块-json、pickle、shelve
json模块 用于文件处理时其他数据类型与js字符串之间转换.在将其他数据类型转换为js字符串时(dump方法),首先将前者内部所有的单引号变为双引号,再整体加上引号(单或双)转换为js字符串:再使用 ...
- 常用文件操作模块json,pickle、shelve和XML
一.json 和 pickle模块 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换 Js ...
- python json、 pickle 、shelve 模块
json 模块 用于序列化的模块 json,用于字符串 和 python数据类型间进行转换 Json模块提供了四个功能:dumps.dump.loads.load #!/usr/bin/env pyt ...
- 第九节:os、sys、json、pickle、shelve模块
OS模块: os.getcwd()获取当前路径os.chdir()改变目录os.curdir返回当前目录os.pardir()父目录os.makedirs('a/b/c')创建多层目录os.remov ...
- (十四)json、pickle与shelve模块
任何语言,都有自己的数据类型,那么不同的语言怎么找到一个通用的标准? 比如,后端用Python写的,前端是js,那么后端如果传一个dic字典给前端,前端肯定不认. 所以就有了序列化这个概念. 什么是序 ...
随机推荐
- vue搭建脚手架
1.检查npm -v有版本提示成功即可2.npm install vue-cli -g //全局安装3.vue -V 查看版本号(我这边安装的是2.9.6,V大写)4.vue init webpack ...
- [LeetCode] 系统刷题3_Binary search
可以参考 [LeetCode] questions conclusion_ Binary Search
- Python基础学习之Python主要的数据分析工具总结
Python主要是依靠众多的第三方库来增强它的数据处理能力的.常用的是Numpy库,Scipy库.Matplotlib库.Pandas库.Scikit-Learn库等. 常规版本的python需要在安 ...
- phpstudy----------如何将phpstudy里面的mysql升级到指定版本,如何升级指定PHP版本
1.下载指定版本:从官网上下载高版本的 MySQL :https://dev.mysql.com/downloads/file/?id=467269,选的版本是 5.7.17 2.请注意第四部以前是可 ...
- docker安装配置gitlab详细过程
docker安装配置gitlab详细过程 获取镜像 1.方法一 1 docker pull beginor/gitlab-ce:11.0.1-ce.0 2.方法二如果服务器网路不好或者pull不下 ...
- select2 api参数中文文档
select2 api参数的文档 具体参数可以参考一下: 参数 类型 描述 Width 字符串 控制 宽度 样式属性的Select2容器div minimumInputLength int 最小数 ...
- easy ui datatimebox databox 当前时间
databox 当前日期: class="easyui-datebox" var curr_time = new Date(); var strDate = curr_time. ...
- DRF之解析器源码解析
解析器 RESTful一种API的命名风格,主要因为前后端分离开发出现前后端分离: 用户访问静态文件的服务器,数据全部由ajax请求给到 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己 ...
- 正则表达式中test,match,exec区别
testtest 返回 Boolean,查找对应的字符串中是否存在模式.var str = "1a1b1c";var reg = new RegExp("1." ...
- [转载]Oracle Golden Gate - 概念和机制 (ogg)
出处:https://www.cnblogs.com/qiumingcheng/p/5435907.html Golden Gate(简称OGG)提供异构环境下交易数据的实时捕捉.变换.投递. OGG ...