python用pickle模块实现“增删改查”的简易功能

yipeiwu_com5年前Python基础

pickle的作用:

1:pickle.dump(dict,file)把字典转为二进制存入文件.

2:pickle.load(file)把文件二进制内容转为字典

import pickle

# 增 
def adds(): 
  users = {"name":"yangbin", "age":22, "sex":"male"} 
  with open("red.txt", "wb") as f: 
    pickle.dump(users, f)
  dic = {} 
  with open("red.txt") as sd: 
    dic = pickle.load(sd) 
  print dic

# 删 
def deletes():
  dic = {} 
  with open("red.txt") as f: 
    dic = pickle.load(f)
  dic.pop("sex")
  with open("red.txt", "wb") as ff: 
    pickle.dump(dic, ff) 
  print dic 

# 改 
def changes(): 
  dic = {}
  with open("red.txt") as f: 
    dic = pickle.load(f) 
  dic["age"] = 28 
  with open("red.txt", "wb") as f: 
    pickle.dump(dic, f) 
  print dic

# 查 
def finds(): 
  dic = {}
  with open("red.txt") as f: 
    dic = pickle.load(f) 
  for k,v in dic.items():
    print "%s ---> %s" % (k, v) 

adds() 
deletes() 
changes()
finds()

运行结果:

root@python3:/python/python2/linshi# python 01.py 
{'age': 22, 'name': 'yangbin', 'sex': 'male'}
{'age': 22, 'name': 'yangbin'}
{'age': 28, 'name': 'yangbin'}
age ---> 28
name ---> yangbin
root@python3:/python/python2/linshi#

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 垃圾收集机制的实例详解

 python 垃圾收集机制的实例详解 pythonn垃圾收集方面的内容如果要细讲还是挺多的,这里只是做一个大概的概括 Python最主要和绝大多数时候用的都是引用计数,每一个...

Python通过递归获取目录下指定文件代码实例

这篇文章主要介绍了python通过递归获取目录下指定文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 获取一个目录下所有指定...

用python打印1~20的整数实例讲解

用python打印1~20的整数实例讲解

while语句打印1-20的整数,并且每行打印五个数,为了实现每行5个数,我们使用一个if判断语句来实现,判断当打印出5个数之后,自动换行打印出来,直至完全输出来。希望对正在学习pyth...

对python3 Serial 串口助手的接收读取数据方法详解

其实网上已经有许多python语言书写的串口,但大部分都是python2写的,没有找到一个合适的python编写的串口助手,只能自己来写一个串口助手,由于我只需要串口能够接收读取数据就可...

对python中assert、isinstance的用法详解

1. assert 函数说明: Assert statements are a convenient way to insert debugging assertions into a...