#coding:utf-8
__author__ = 'similarface'
#email:similarface@outlook.com
'''
shelve模块:
映射容器
存储对象,被存储的对象都会被序列化并且被写入文件
反序列化然后从文件获取任意对象 method:shelve.open()
'r' Open existing database for reading only (default)
'w' Open existing database for reading and writing
'c' Open database for reading and writing, creating it if it doesn’t exist
'n' Always create a new, empty database, open for reading and writing
'''
import shelve
import logging
logging.basicConfig(level=logging.DEBUG)
console = logging.StreamHandler()
logging.getLogger('').addHandler(console)
class Person:
'''
定义个简单的类
'''
def __init__(self,name,*posts):
self.name=name def as_dict(self):
return dict(name=self.name,underline="="*len(self.name),) p1=Person(name='Tom')
#创建shelf对象
shelf=shelve.open('person')
#设置键
p1._id='person:1'
#存储
shelf[p1._id]=p1 #获取
p=shelf[p1._id]
logging.info(p)
logging.info(p.name)
logging.info(p._id)
logging.info(list(shelf.keys()))
shelf.close()
#获取存储对象
shelf=shelve.open('person')
#获取指定的对象 根据类和属性来获取
results=(shelf[k] for k in shelf.keys() if k.startswith('person:') and shelf[k].name=='Tom' )
#logging.info(list(results))
for i in results:
r0=i
logging.info(r0._id)
logging.info(r0.name) '''
INFO:root:<__main__.Person instance at 0x00000000026DBAC8>
<__main__.Person instance at 0x00000000026DBAC8>
INFO:root:Tom
Tom
INFO:root:person:1
person:1
INFO:root:['person:1']
['person:1']
INFO:root:person:1
person:1
INFO:root:Tom
Tom
''' '''
存在继承的对象的持久化
使用外键引用对象
''' import datetime
class Teacher:
def __init__(self,profession,name,desc,tags):
self.profession=profession
self.name=name
self.desc=desc
self.tags=tags def as_dict(self):
return dict(
profession=self.profession,
name=self.name,
underline="-"*len(self.name),
desc=self.desc,
tags=" ".join(self.tags)
) t1=Teacher('math','Lucy','beauifu teacher',['senior'])
t2=Teacher('english','Tom','Stronger',['lower']) import shelve
shelf=shelve.open('person')
owner=shelf['person:1']
t1._parent=owner._id
t1._id=t1._parent+':teacher:1'
shelf[t1._id]=t1 t2._parent=owner._id
t2._id=t2._parent+':teachar:2'
shelf[t2._id]=t2 logging.info(list(shelf.keys()))
logging.info(t1._parent)
logging.info(t2._id) '''
INFO:root:['person:1:teachar:2', 'person:1', 'person:1:teacher:1']
['person:1:teachar:2', 'person:1', 'person:1:teacher:1']
INFO:root:person:1
person:1
INFO:root:person:1:teachar:2
person:1:teachar:2
'''

  

shelve模块的更多相关文章

  1. python序列化: json & pickle & shelve 模块

    一.json & pickle & shelve 模块 json,用于字符串 和 python数据类型间进行转换pickle,用于python特有的类型 和 python的数据类型间进 ...

  2. python pickle 和 shelve模块

    pickle和shelve模块都可以把python对象存储到文件中,下面来看看它们的用法吧 1.pickle 写: 以写方式打开一个文件描述符,调用pickle.dump把对象写进去 dn = {'b ...

  3. s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译

    时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...

  4. 小白的Python之路 day5 shelve模块讲解

    shelve模块讲解 一.概述 之前我们说不管是json也好,还是pickle也好,在python3中只能dump一次和load一次,有什么方法可以向dump多少次就dump多少次,并且load不会出 ...

  5. python之shelve模块详解

    一.定义 Shelve是对象持久化保存方法,将对象保存到文件里面,缺省(即默认)的数据存储文件是二进制的. 二.用途 可以作为一个简单的数据存储方案. 三.用法 使用时,只需要使用open函数获取一个 ...

  6. Python全栈之路----常用模块----序列化(json&pickle&shelve)模块详解

    把内存数据转成字符,叫序列化:把字符转成内存数据类型,叫反序列化. Json模块 Json模块提供了四个功能:序列化:dumps.dump:反序列化:loads.load. import json d ...

  7. os常用模块,json,pickle,shelve模块,正则表达式(实现运算符分离),logging模块,配置模块,路径叠加,哈希算法

    一.os常用模块 显示当前工作目录 print(os.getcwd()) 返回上一层目录 os.chdir("..") 创建文件包 os.makedirs('python2/bin ...

  8. json,pickle,shelve模块,xml处理模块

    常用模块学习—序列化模块详解 什么叫序列化? 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化? 你打游戏过程 ...

  9. python的shelve模块

    shelve shelve是一额简单的数据存储方案,他只有一个函数就是open(),这个函数接收一个参数就是文件名,并且文件名必须是.bat类型的.然后返回一个shelf对象,你可以用他来存储东西,就 ...

随机推荐

  1. MySql5.7-多源复制(多主单从)

    1.1.主库配置 my.cnf   #确保唯一 server-id=1 #作为Master要开启binlog log-bin=mysql-bin #binlog format有三种形式:Stateme ...

  2. Codeforces Canada Cup 2016

    A. Jumping Ball time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...

  3. boost库学习之开篇

    本系列文章使用boost_1.58.0版本. 一.欢迎使用boost C++库 boost致力于提供一个免费的.便携的源代码级的库. 我们重视那些与C++标准一起工作良好的库.boost库将要成为一个 ...

  4. easyUI的window包含一个iframe,在iframe中如何关闭window?

    easyUI的window包含一个iframe,在iframe中如何关闭window? parent.$('#win').window('close');

  5. reactjs入门到实战(十)----one-first_app

    index <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- ...

  6. WebForm分页浏览

    1.封装类 //封装类 using System; using System.Collections.Generic; using System.Web; /// <summary> // ...

  7. log4j---------学习总结(一)

    一.log4j框架 log4j可靠的,快速的,可扩展的(灵活的)日志框架 log4j具有高可配置性,可以通过外部配置文件来控制 log4j可以根据日志不同级别来过滤日志, log4j可以将日志记录直接 ...

  8. Cheatsheet: 2014 02.01 ~ 02.28

    Database Managing disk space in MongoDB When to use GridFS on MongoDB .NET The Past, Present, and Fu ...

  9. 【转载】如何系统地自学 Python?

    原文:如何系统地自学 Python? 作者:彭猫 本文由 知乎 彭猫 授权发布,版权所有归作者,转载请联系作者! 是否非常想学好 Python,一方面被琐事纠缠,一直没能动手,另一方面,担心学习成本太 ...

  10. Lucky String

    Lucky String -- 微软笔试 标签(空格分隔): 算法 A string s is LUCKY if and only if the number of different charact ...