python模块--pickle&json&shelve
使用file文件处理时,写入的必须是str ,否则会报错。
例如:要把一个字典写入文件,写入时会报错 ,就算转换成str格式写入,读取的时候也不能按照dict格式读。
>>> info={
... 'jack':123,
... 'lily':''
... }
>>> with open('test.txt','w') as f:
... f.write(info)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: write() argument must be str, not dict
序列化
pickle 能够序列化更多的格式,复杂的类型也能处理。例如函数,类等
json 只支持简单类型,如数字,字典,元祖
pickle模块 ( python独有的)
#dumps & loads
# pickle.dumps 将数据转化成只有python认识的字节
>>> p=pickle.dumps(123) #序列化
>>> print(p)
b'\x80\x03K{. >>> pickle.loads(p) #读取,反序列化
123 # dump & load
# pickle.dump 将数据转化成只有python认识的字节,并写入文件
>>> with open('test.txt','wb') as f:
... pickle.dump(info,f)
...
>>> with open('test.txt','rb') as f:
... pickle.load(f)
...
{'jack': 123, 'lily': ''}
json模块 (所有语言都支持)
# dumps & loads
# json.dumps 将数据转化成字符串
>>> import json
>>> import pickle
>>> j = json.dumps(['a','b','c']) #把列表转化成字符串
>>> j
'["a", "b", "c"]'
>>> json.loads(j) #把字符串转化成列表
['a', 'b', 'c'] # dump & load
# json.dump 将数据转化成字符串,并写入文件
>>> with open('test.txt','w') as f:
... json.dump({'user':'lily'},f)
...
>>> with open('test.txt','r') as f:
... json.load(f)
...
{'user': 'lily'}
yaml 模块
把字典写成yml格式的文件:
import yaml
my_dict={'people':{'name':'lily','city':'深圳'}}
with open('info.yml','w') as f:
yaml.dump(my_dict,f,allow_unicode=True) # allow_unicode=True转化成unnicode形式,否则写入文件中文会显示成unicode格式 # cat info.yml
people:
city: 深圳
name: lily
读取yaml格式的文件:
import yaml
with open('info.yml') as f:
data = yaml.load(f)
print(data)
----->
{'people':{'name':'lily','city':'深圳'}}
shelve -python对象持久化
shelve 通过k,v的格式将内存数据通过文件持久化
键是普通的字符串。值可以是任意的python对象- 任何pickle模块可以处理的类型
好处:方便多次存数据,随时通过key来取数据,类似字典操作
创建一个shelve:
import shelve
l = ['a','b','c']
d = {"name":"lily","age":22}
s = shelve.open('shelve_test')
s['key_list'] = l
s['key_dict'] = d
s.close() #结果:会生成三个文件 shelve_test.bak,shelve_test.dat ,shelve_test.dir
读取文件内容:
s = shelve.open('shelve_test')
print(s['key_list']) #类似dict取值的方法,如果key不存在会报KeyError
print(s.get('key_dict')) #get()方法,如果key不存在,返回None
s.close()
结果:
['a', 'b', 'c']
{'name': 'lily', 'age': 22}
遍历所有数据:
with shelve.open("shelve_test") as s:
for i in s:
print(i,s[i])
修改shelve已经存在的key的值的数据。 需要加上写回(Writeback=True),否则修改不会生效
s = shelve.open('shelve_test',writeback=True)
s['key_list'].append('defg')
s['key_list'][0] = 'first'
s.close()
#再读取
s = shelve.open('shelve_test')
print(s['key_list'])
s.close()
#结果:
['a', 'b', 'c', 'defg']
也可以通过with,防止打开之后忘记关闭close()
with shelve.open("selve_test") as s:
s['key4'] = 444
print(s.get('key4'))
#结果 444
python模块--pickle&json&shelve的更多相关文章
- python模块之JSON
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之JSON #1.JSON #JSON表示的对象就是标准的JavaScript语言的对象 # ...
- python的pickle和shelve模块
python中用于序列化的模块总结 目录 pickle模块 shelve模块 xml模块 pickle模块 介绍 Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python, ...
- python 模块 - 序列化 json 和 pickle
1,引入 之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval ...
- python3之序列化(pickle&json&shelve)
1.pickle模块 python持久化的存储数据: python程序运行中得到了一些字符串,列表,字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据.python ...
- 第二十二天- 序列化 pickle json shelve
# 序列化:存储或传输数据时,把对象处理成方便存储和传输的数据格式,这个过程即为序列化# Python中序列化的三种方案:# 1.pickle python任意数据——>bytes写入⽂件:写好 ...
- Learn day6 模块pickle\json\random\os\zipfile\面对对象(类的封装 操作 __init__)
1.模块 1.1 pickle模块 # ### pickle 序列化模块 import pickle """ 序列化: 把不能够直接存储的数据变得可存储 反序列化: 把数 ...
- python 模块之-json
python 模块json import json x="[null,true,false,1]" print(json.loads(x)) #---------------- ...
- python使用pickle,json等序列化dict
import pickle, json, csv, os, shutil class PersistentDict(dict): ''' Persistent dictionary with an A ...
- day21 pickle json shelve configpaser 模块
1. 序列化:我们在网络传输的时候,需要我们对对象进行处理,把对象处理成方便存储和传输的格式,这个过程就叫序列化 序列化的方法不一定一样,三十目的都是为了方便储存和传输. 在python中有三种序列化 ...
随机推荐
- GCD与莫比乌斯反演的勾当
目录 机房最后一个学懵逼钨丝的人 题目一 题目 bzoj1101 机房最后一个学懵逼钨丝的人 题目一 链接 题目没找到 求\(\sum_{1}^{n}\sum_{1}^{m}gcd(i,j)\) 式子 ...
- Basic Mathematics You Should Mastered
Basic Mathematics You Should Mastered 2017-08-17 21:22:40 1. Statistical distance In statistics, ...
- java.lang.OutOfMemoryError:GC overhead limit exceeded
在调测程序时报java.lang.OutOfMemoryError:GC overhead limit exceeded 错误 错误原因:在用程序进行数据切割时报了该错误.由于在本地执行数据切割测试的 ...
- java中Properties类及读取properties中属性值
本文为博主原创,未经允许不得转载: 在项目的应用中,经常将一些配置放入properties文件中,在代码应用中读取properties文件,就需要专门的类Properties类,通过这个类可以进行读取 ...
- ISTQB学习笔记
学习ISTQB大纲此文记录初次阅读时不够明确的地方 第一章:软件测试基础1. 引起软件缺陷的原因人都会犯错误(error,mistake),因此人设计的代码或文档中会引入缺陷(defect, faul ...
- JS计算前一天或后一天,前一月后一月
JS计算前一天或后一天,前一月后一月,上一天下一下,上一月下一月. 方法一: function ktkGetNextMonth(currentDate, scaleStep) { //scaleSte ...
- Shell 脚本批量创建数据库表
使用 Shell 脚本批量创建数据表 系统:Centos6.5 64位 MySQL版本:5.1.73 比如下面这个脚本: #!/bin/bash #批量新建数据表 for y in {0..199}; ...
- 草珊瑚理解IFC(inline formatting context)
1. 认识字体font-family 字体渲染的实际高度, 由字体本身的设置(升部ascender,降部descender,大写字母高度Capital Height,小写字母高度X-Height等等) ...
- 网站项目所有js css无法引用问题解决方案
网站页面中的所有js css引用失效,路径确保正确,但是浏览器就是报找不到引用.仔细查找发现问题所在: 报错信息很详细了,就是.NET Framework 版本不同导致.同时也提供了两个解决方案:将. ...
- hdu 1011 Starship Troopers 树形背包dp
Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...