博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python的一些常用标准库
阅读量:6862 次
发布时间:2019-06-26

本文共 7365 字,大约阅读时间需要 24 分钟。

序列化模块

将原本字典,元组,列表等内容型转化为字符串,以便于存储或者传输操作.

目的

1.以某种储存形式使定义对象持久化,说白了就是将对象储存为文件,而不是在内存中

2.将对象传输时只能使用byts类型,这就需要一些字符串和bytes类型的转化知识了

3.使程序更加的便于维护,

 

str通过序列化为数据结构

数据结构通过反序列化转化为str

 

三个大模块

josn#用于字典 或者列表 其他的多语言可以使用   ""两个引号为josn   单引号为字符串  josn特有 其他语言特有,python不计较这些

dumps      loads      转化

dump       load         直接转化写入文件

pickle  python特有,可以将所有数据类型转化

dumps      loads      转化

dump       load    直接转化写入文件

shelve python提供的工具,可以读取或者存储数据

open   通过key来访问, 存入或者读取数据

 

 

 

实例:

jsonJson模块提供了四个功能:dumps、dump、loads、load复制代码import jsondic = {
'k1':'v1','k2':'v2','k3':'v3'}str_dic = json.dumps(dic) #序列化:将一个字典转换成一个字符串print(type(str_dic),str_dic) #
{"k3": "v3", "k1": "v1", "k2": "v2"}#注意,json转换完的字符串类型的字典中的字符串是由""表示的dic2 = json.loads(str_dic) #反序列化:将一个字符串格式的字典转换成一个字典#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示print(type(dic2),dic2) #
{'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) #
[1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]list_dic2 = json.loads(str_dic)print(type(list_dic2),list_dic2) #
[1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]复制代码复制代码import jsonf = 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)复制代码复制代码import jsonf = 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()复制代码复制代码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 jsondata = {
'username':['李华','二愣子'],'sex':'male','age':16}json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)print(json_dic2)
josn
pickle json & pickle 模块 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换pickle,用于python特有的类型 和 python的数据类型间进行转换 pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load  (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化) 复制代码import pickledic = {
'k1':'v1','k2':'v2','k3':'v3'}str_dic = pickle.dumps(dic)print(str_dic) #一串二进制内容dic2 = pickle.loads(str_dic)print(dic2) #字典import timestruct_time = time.localtime(1000000000)print(struct_time)f = open('pickle_file','wb')pickle.dump(struct_time,f)f.close()f = open('pickle_file','rb')struct_time2 = pickle.load(f)print(struct_time2.tm_year)复制代码 这时候机智的你又要说了,既然pickle如此强大,为什么还要学json呢?这里我们要说明一下,json是一种所有的语言都可以识别的数据结构。如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle
pickle
shelveshelve也是python提供给我们的序列化工具,比pickle用起来更简单一些。shelve只提供给我们一个open方法,是用key来访问的,使用起来和字典类似。复制代码import shelvef = shelve.open('shelve_file')f['key'] = {
'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据f.close()import shelvef1 = shelve.open('shelve_file')existing = f1['key'] #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错f1.close()print(existing)复制代码这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DBimport shelvef = shelve.open('shelve_file', flag='r')existing = f['key']f.close()print(existing)由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。复制代码import shelvef1 = 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()复制代码writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。
shevle

 

 

上课的笔记

# 序列化  数据类型 列表 元组 字符串# 只有字符串能被写入文件中# 能在网络上传输的只能是bytes -字符串# 把要传输的和要存储的内容 转换成 字符串# 字符串 转换回 要传输和存储的内容# 序列化只有两种作用    # 网络传输    # 数据持久化 - 写在文件里# json# pickle# shelve# d = {'key1':'value1','key2':'value2'}# print(d)# print(str(d),type(str(d)))  # 序列化# print(eval(str(d)),type(eval(str(d)))) # 反序列化# import json# d = {'key1':'value1','key2':'value2'}# ret = json.dumps(d)   # 序列化# print(ret,type(ret))  # json# dic = json.loads(ret)# print(dic,type(dic))  # 反序列化操作#dump load 用在文件操作数据类型的序列化与反序列化上# with open('json_sample','w') as f:#     json.dump(d,f)# with open('json_sample','r') as f:#     print(type(json.load(f)))# with open('json_sample3','r') as f:#     for line in f:#         ret = json.loads(line.strip())#         print(ret,type(ret))# dumps loads# dump loadimport json# data = {'username':['李华','二愣子'],'sex':'male','age':16}# json_dic2 = json.dumps(data,sort_keys=True,indent=10,separators=(',',':'),ensure_ascii=False)# print(json_dic2)# data = {'username':['李华','二愣子'],'sex':'male','age':16}# with open('json_sample','w',encoding='utf-8') as f:#     json.dump(data,f,ensure_ascii=False)# with open('json_sample','r',encoding='utf-8') as f:#     print(json.load(f))#pickledata = {
'username':['李华','二愣子'],'sex':'male','age':16}import pickle# ret = pickle.dumps(data)# print(ret)# print(pickle.loads(ret))# with open('pickle_sample','wb') as f:# pickle.dump(data,f)# pickle.dump(data,f)# with open('pickle_sample','rb') as f:# print(pickle.load(f))# print(pickle.load(f))# 1.pickle模块 dumps之后是bytes# 2.pickle模块 dump之后的内容在文件中是乱的# 3.pickle模块可以连续dump数据进入文件,然后连续load出来# 4.pickle可以任意的将python中的数据类型序列化# json只能对列表 字典 进行序列化# class A:pass # 程序# a = A()# b = pickle.dumps(a)# print(b)# print(pickle.loads(b))import shelve# f = shelve.open('shelve_file')# f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据# f.close()# key:{'int':10, 'float':9.5, 'string':'Sample data'}# import shelve# f1 = shelve.open('shelve_file')# existing = f1['key'] #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错# f1.close()# print(existing)# import shelve# f1 = shelve.open('shelve_file',writeback=True)# f1['key']['new_value'] = 'this was not here before'# f1.close()## f1 = shelve.open('shelve_file')# print(f1['key'])# f1.close()
上课笔记演示

 

转载于:https://www.cnblogs.com/cangshuchirou/p/8493234.html

你可能感兴趣的文章
[产品经理手记-02] 培训二三事
查看>>
个人作业 感想
查看>>
Cap15_知识管理
查看>>
【2012百度之星资格赛】F:百科蝌蚪团
查看>>
【解决方法】Ubuntu文本编辑器gedit打开中文出现乱码的
查看>>
【linux】ubuntu11.10下各种问题以及解决方案
查看>>
C++指针
查看>>
Python学习第一二章
查看>>
Docker学习笔记二:Docker常用命令及提升拉取镜像的速度
查看>>
Python操作Oracle
查看>>
Algs4-2.1.38不同类型的元素
查看>>
MapReduce源码分析总结(转)
查看>>
linux cpu、内存、硬盘空间查询
查看>>
idea 启动调试模式总提示端口58346被占用问题
查看>>
Pro JPA2读书笔记系列(八)-第八章(查询语言)
查看>>
oracle目录操作
查看>>
主流ETL工具
查看>>
fileinput 图片上传
查看>>
UUID
查看>>
Selenium2+Python--下拉选择用select
查看>>