Home > Backend Development > Python Tutorial > python pickle 和 shelve模块的用法

python pickle 和 shelve模块的用法

WBOY
Release: 2016-06-16 08:46:30
Original
1220 people have browsed it

1.pickle

   写: 以写方式打开一个文件描述符,调用pickle.dump把对象写进去

复制代码 代码如下:

    dn = {'baidu':'www.baidu.com','qq':'www.qq.com','360':'www.360.cn'}

    name = ['mayun','mahuateng','liyanhong']

    f = open(r'C:\a.txt','w')

    pickle.dump(dn,f)      ##写一个对象

    pickle.dump(name,f)  ##再写一个对象

    f.close() 

   读:以读的方式打开文件描述符,调用pickle.load加载对象

    f = open(r'C:\a.txt')

    pickle.load(f)             ##加载一个对象

    pickle.load(f)             ##加载另一个对象

    f.close()


2.shelve

   shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写

复制代码 代码如下:

   f = shelve.open(r'C:\b.txt')

   f  ##返回空字典

   f['baidu'] = 'www.baidu.com'

   f['qq'] = 'www.qq.com'

   f['360'] = 'www.360.cn'

   f  ##返回字典

   f.close()

   f = shelve.open(r'C:\b.txt')

   f ##返回字典f

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template