美文网首页
9. 初识数据存储与读取shelve函数

9. 初识数据存储与读取shelve函数

作者: 闪电侠悟空 | 来源:发表于2017-07-10 23:04 被阅读0次

    很多情况下,我们需要读取和写入少量的数据(远小于GB的量级)。在Matlab中采用save和load 两个函数,能够轻松的将变量空间的值存入到文件,也可轻松的将数据值从文件读取到当前活动workspace (类似与python的作用域 scope),我们不用去关注存储方式(二进制或者ascii码)。 Python有这样的函数么?答案你肯定猜到了!他就是shelve模块

    • 如何打开文件和关闭文件?
    • 如何存储和读取数据?

    如何打开文件?

    import shelve
    s = shelve.open(filename, flag='c', protocol=None, writeback=False)
    

    解释函数的输入参数之前,回顾下python作用域中的变量是以何种方式存储的?字典(及其类似物,见下面代码)。那么返回值s也就是一个类似的字典 (此处为什么不用f表示而用s呢?可以想想)。

    >>> x = 10
    >>> vars()
    { 'x': 10, '__name__': '__main__', '__spec__': None,...}
    
    • filename 就不需要解释了吧
    • 参数flag表明的是文件的读写权限,下表内容来自'官网'
    Value Meaning
    '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
    • protocal(协议,规则) 是什么鬼?肯定是和存储相关的。参数protocol是序列化模式,默认值为0,表示以文本的形式序列化。protocol的值还可以是1或2,表示以二进制的形式序列化。

    关闭文件的方式很简单

    s.close
    

    为了保证文件顺利关闭,当然也有复杂的方式(try:finally:语句和 with 语句)

    >>> s = shelve.open('test.dat')
    >>> dir(s)
    [ '__exit__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', 'close', 'dict', 'get', 'items', 'keyencoding', 'keys', 'pop', 'popitem',...]
    

    具有魔法方法__exit__的对象都可以使用设备上下文的方式关闭。

    如何存储和读取数据?

    如果文件test.dat中没有写入任何东西, 你是读取不到任何数据的。
    那么就有必要写入数据,记住,shelve是基于字典的操作。
    所以,写入数据很简单。

    >>> s = shelve.open('test.dat')
    >>> len(s) # 空的文件没有存储数据
    0
    >>> s['x'] = 'flash'
    >>> s['y'] = [1,2,3]
    >>> s.close()
    >>> s2 = shelve.open('test.dat','r')
    >>> len(s2)
    2
    >>> s2['x']
    'flash'
    >>> s2['y']
    [1, 2, 3]
    

    最终的代码

    >>> with shelve.open('test.dat') as s: #使用with 语句就不需要s.close()操作了。
    ...     for iter in s:
    ...         print(iter,s[iter])
    ... 
    x flash
    y [1, 2, 3]
    

    相关文章

      网友评论

          本文标题:9. 初识数据存储与读取shelve函数

          本文链接:https://www.haomeiwen.com/subject/mqauhxtx.html