序列化模块— json模块,pickle模块,shelve模块

时间:2022-09-02 08:12:42

json模块

pickle模块

shelve模块

序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化。

序列化模块— 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模块的更多相关文章

  1. 【转】Python之数据序列化(json、pickle、shelve)

    [转]Python之数据序列化(json.pickle.shelve) 本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型 ...

  2. python常见模块之序列化(json与pickle以及shelve)

    什么是序列化? 我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flatte ...

  3. 20,序列化模块 json,pickle,shelve

    序列化模块 什么叫序列化? 将原本的字典,列表等内容转换成一个字符串的过程叫做序列化. 序列化的目的? 数据结构 通过序列化 转成 str. str 通过反序列化 转化成数据结构. json: jso ...

  4. Python—序列化和反序列化模块&lpar;json、pickle和shelve&rpar;

    什么是序列化 我们把对象(或者变量)从内存中变为可存储或者可传输的过程称为序列化.在python中为pickling,在其他语言中也被称之为serialization,marshalling,flat ...

  5. os常用模块,json,pickle,shelve模块,正则表达式(实现运算符分离),logging模块,配置模块,路径叠加,哈希算法

    一.os常用模块 显示当前工作目录 print(os.getcwd()) 返回上一层目录 os.chdir("..") 创建文件包 os.makedirs('python2/bin ...

  6. python模块-json、pickle、shelve

    json模块 用于文件处理时其他数据类型与js字符串之间转换.在将其他数据类型转换为js字符串时(dump方法),首先将前者内部所有的单引号变为双引号,再整体加上引号(单或双)转换为js字符串:再使用 ...

  7. 常用文件操作模块json,pickle、shelve和XML

    一.json 和 pickle模块 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换 Js ...

  8. python json、 pickle 、shelve 模块

    json 模块 用于序列化的模块 json,用于字符串 和 python数据类型间进行转换 Json模块提供了四个功能:dumps.dump.loads.load #!/usr/bin/env pyt ...

  9. 第九节:os、sys、json、pickle、shelve模块

    OS模块: os.getcwd()获取当前路径os.chdir()改变目录os.curdir返回当前目录os.pardir()父目录os.makedirs('a/b/c')创建多层目录os.remov ...

  10. (十四)json、pickle与shelve模块

    任何语言,都有自己的数据类型,那么不同的语言怎么找到一个通用的标准? 比如,后端用Python写的,前端是js,那么后端如果传一个dic字典给前端,前端肯定不认. 所以就有了序列化这个概念. 什么是序 ...

随机推荐

  1. jquery图片轮播

    <html> <head> <title>position</title> <style type="text/css"&gt ...

  2. Android成长日记-ListView

    数据适配器:把复杂的数据(数组,链表,数据库,集合等)填充在指定的视图界面上 适配器的类型: ① ArrayAdapter(数组适配器):用于绑定格式单一的数据 数据源:可以是集合或数组 ① Simp ...

  3. iOS 中的 block 是如何持有对象的

    Block 是 Objective-C 中笔者最喜欢的特性,它为 Objective-C 这门语言提供了强大的函数式编程能力,而最近苹果推出的很多新的 API 都已经开始原生的支持 block 语法, ...

  4. Yii 安装二维码扩展Qrcode

    比如要添加 https://github.com/2amigos/yii2-qrcode-helper 生成二维码的 这个扩展第一种方法 :    1.打开根目录的composer.json, 在re ...

  5. eclipse - tomcat 远程调试

    步骤:前提是tomcat上应用是eclipse打包部署上去的,代码一致. 1,在机器A上部署应用remote-debug之前,需要为机器A上的tomcat配置调试端口.在${tomcat}/bin下加 ...

  6. Tar专题

    下面的脚本根据当前的系统时间生成压缩文件名,并备份文件到指定目录: DIR=/www/webbackup/web/ FILE_NAME=`date +%y%m%d%H` FILE_NAME=$DIR/ ...

  7. 微信小程序之图片base64解码

    不知道大家在做微信小程序的时候遇到base64解码的问题,我之前在做微信小程序的时候遇到base64解析图片一直有问题,所以在这里把遇到的问题和解决方案在这里记录一下: 在平时的项目中我们是直接用ba ...

  8. switch and checkbox

    import 'package:flutter/material.dart'; void main()=>runApp(MyApp()); class MyApp extends Statele ...

  9. 微信小程序 &vert; 多个按钮或VIEW,切换状态的简单方法&lpar;三元&rpar;

    wxml文件 wxss文件 js文件

  10. &lbrack;转&rsqb;ubuntu安装skype

    Skype 4.3 Released, How to Install it in Ubuntu 14.04/12.04 June 19, 2014 — 107 Comments   Skype for ...