Python中shelve模块的简单介绍(附示例)


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于Python中shelve模块的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

shelve:对象持久化的保存的模块,将对象保存到文件里 (默认的数据存储文件为二进制),可持久化任何pickle可支持的Python数据格式

shelve 中唯一的方法:

shelve.open(filename,flag = 'c', protocol = None , writebake = False)

filename关联的文件路径
flag 'r' :以只读模式打开一个已经存在的数据存储文件
'w' :以读写模式打开一个已经存在的数据存储文件
'c' :(默认)以读写模式打开一个数据存储文件,如果不存在则创建
'n' :总是以读写模式打开并且创建一个新的空数据存储文件
protocol表示序列化数据所使用的协议,默认为 None(pickle v3)
writebake表示是否开启回写功能

1. 文件可以像字典一样存储key - value (注:key 必须为字符串,value 可以是任何数据类型)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import shelve

date = shelve.open('family.txt')         # Python的自处理系统会自动生成三个文件

date['father'] = 'Presly'                        # 默认为创建并且写入“c”

date['mather'] = 'Vera'

date['baby'] = [123, ]

date.close()

m = shelve.open('family.txt', falg= 'r', writebake=True)          # 当writebake设置为True时,文件里才能直接添加

print(m['baby'])

m['baby'].append(345)

print(m['father'])

print('-------------')

for key, value in m.items():           # 以字典的格式

    print(key, ':', value)

m.close()

1

2

3

4

5

6

[123]

Presly

-------------

father : Presly

mather : Vera

baby : [123,345]

2. shelve 的序列化

  • 可以把类的数据序列化,然后再 反序列化出元素

  • 与pickle不同的是,pickle只能按照dump顺序,load出元素,而shelve可以直接重复拿出不同或者相同存进文件的key值,

3. shelve 可以进行类似于库,增,删,改,查

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

import shelve

 

 

def store_information(database):

    info = {}

    ID = input('Enter the ID number:')

    info['name'] = input('Enter the name:')         # 将name ,age , phone 存入字典info里

    info['age'] = input('Enter the age:')

    info['phone'] = input('Enter the phone:')

    database[ID] = info                            # 用ID : info 存入 database文件

 

 

def lookup_information(database):

    ID = input('Enter the ID:')

    field = input('What would you like to know?(name,age,phone)')

    field = field.strip().lower()

    print(database[ID][field])              # 通过输入的ID与 field 直接打印结果

 

 

def print_help():

    print('Please enter the help command:')

    print('store  :store informatinon to database')

    print('lookup :look up information by numID')

    print('quit   :save information and quit')

    print('?      :print help command')

 

 

def enter_command():

    cmd = input('Enter command (? for help)')

    cmd = cmd.strip().lower()

    return cmd

 

 

def main():

    database = shelve.open('db.dat')

    try:

        while True:

            cmd = enter_command()

            if cmd == 'store':

                store_information(database)           # 当if函数结束,自动跳转到cmd = enter_command()行

            elif cmd == 'lookup':

                lookup_information(database)

            elif cmd == '?':

                print_help()

            elif cmd == 'quit':

                return                            # 跳出while循环

    finally:

        database.close()

 

 

if __name__ == '__main__': main()

以上就是Python中shelve模块的简单介绍(附示例)的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python如何测量脚本运行时间

Python global用法有哪些?

如何查看Python安装路径

Python程序文件的扩展名称是什么

城市经纬度实例代码

Python socket之客户端和服务端握手详细介绍

readline() Python是什么? readline() Python定义及用法解析

qPython可以装requests库吗

linux怎么运行Python脚本?

Python用pip安装numpy

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...