python模块--pickle&json&shelve&yaml

使用file文件处理时,写入的必须是str ,否则会报错。

例如:要把一个字典写入文件,写入时会报错 ,就算转换成str格式写入,读取的时候也不能按照dict格式读。

>>> info={
...      'jack':123,
...      'lily':'1234'
... }

>>> 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'x80x03K{.

>>> 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': '1234'}

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
原文地址:https://www.cnblogs.com/xiaobaozi-95/p/9707982.html