使用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的更多相关文章

  1. python模块之JSON

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之JSON #1.JSON #JSON表示的对象就是标准的JavaScript语言的对象 # ...

  2. python的pickle和shelve模块

    python中用于序列化的模块总结 目录 pickle模块 shelve模块 xml模块 pickle模块 介绍 Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python, ...

  3. python 模块 - 序列化 json 和 pickle

    1,引入 之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval ...

  4. python3之序列化(pickle&json&shelve)

    1.pickle模块 python持久化的存储数据: python程序运行中得到了一些字符串,列表,字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据.python ...

  5. 第二十二天- 序列化 pickle json shelve

    # 序列化:存储或传输数据时,把对象处理成方便存储和传输的数据格式,这个过程即为序列化# Python中序列化的三种方案:# 1.pickle python任意数据——>bytes写入⽂件:写好 ...

  6. Learn day6 模块pickle\json\random\os\zipfile\面对对象(类的封装 操作 __init__)

    1.模块 1.1 pickle模块 # ### pickle 序列化模块 import pickle """ 序列化: 把不能够直接存储的数据变得可存储 反序列化: 把数 ...

  7. python 模块之-json

    python 模块json import json x="[null,true,false,1]" print(json.loads(x))   #---------------- ...

  8. python使用pickle,json等序列化dict

    import pickle, json, csv, os, shutil class PersistentDict(dict): ''' Persistent dictionary with an A ...

  9. day21 pickle json shelve configpaser 模块

    1. 序列化:我们在网络传输的时候,需要我们对对象进行处理,把对象处理成方便存储和传输的格式,这个过程就叫序列化 序列化的方法不一定一样,三十目的都是为了方便储存和传输. 在python中有三种序列化 ...

随机推荐

  1. Kibana --> Getting Started -->Building your own dashboard

    https://www.elastic.co/guide/en/kibana/6.6/tutorial-build-dashboard.html Building your own dashboard ...

  2. Spring Boot 2 入门

    Spring Boot其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 参考网上资料,一路踩了几个坑,终于搞出了 ...

  3. Unity3D学习笔记(三十六):Shader着色器(3)- 光照

    光照模型:用数学的方法模拟现实世界中的光照效果.   场景中模型身上的光反射到相机中的光线: 1.漫反射:产生明暗效果 2.高光反射:产生镜面反射,物体中有最亮且比较耀眼的一部分 3.自发光: 4.环 ...

  4. 使用vue做表单验证

    <template> <Form ref="formInline" :model="formInline" :rules="rule ...

  5. kubernetes 实战5_命令_Assign Pods to Nodes&Configure a Pod to Use a ConfigMap

    Assign Pods to Nodes how to assign a Kubernetes Pod to a particular node in a Kubernetes cluster. Ad ...

  6. HDU 4301 Divide Chocolate(DP)

    http://acm.hdu.edu.cn/showproblem.php?pid=4301 题意: 有一块n*2大小的巧克力,现在某人要将这巧克力分成k个部分,每个部分大小随意,问有多少种分法. 思 ...

  7. HDU 5143 NPY and arithmetic progression(思维)

    http://acm.hdu.edu.cn/showproblem.php?pid=5143 题意: 给定数字1,2,3,4.的个数每个数字能且仅能使用一次,组成多个或一个等差数列(长度大于等于3), ...

  8. 你所要掌握的最简单基础的React渲染优化

    一.React的渲染机制 要掌握一两项React-render优化的方法不难,但是非常重要.无论是在实际项目中的一个小细节,还是迎合'面试官'的口味 1.1 触发Render 我们知道React要更新 ...

  9. jquery.js 3.0报错, Uncaught TypeError: url.indexOf is not a function

    转载自:http://majing.io/questions/432   问题描述 jQuery升级到3.0.0后类型错误 jquery.js:9612 Uncaught TypeError: url ...

  10. javascript 获得以秒计的视频时长

    <!DOCTYPE html> <html> <body> <h3>演示如何访问 VIDEO 元素</h3> <video id=&q ...