• Python学习笔记文件读写之shelve模块保存变量


    随笔记录方便自己和同路人查阅。

    #------------------------------------------------我是可耻的分割线-------------------------------------------

      利用shelve模块,你可以将Python程序中的变量保存到二进制的shelf文件中。这样,程序就可以从硬盘中恢复变量的数据。shelve模块让

    你在程序中添加“保存”和“打开”功能。例如,如果运行一个程序,并输入了一些配置设置,可以将这些设置保存到一个shelf文件,然后让程序下

    一次运行时加载它们。

    #------------------------------------------------我是可耻的分割线------------------------------------------

      1、shelve模块,shelve.open()方法,示例代码:

    #! python 3
    # -*- coding:utf-8 -*-
    # Autor: Li Rong Yang
    import shelve,os
    #使用shelve.open(),打开一个文本文件
    shelfFile = shelve.open('mydata')
    #定义初始化数据列表
    cats = ['Zophie', 'Pooka', 'Simon']
    #把初始化列表赋给shelfFile
    shelfFile['cats'] = cats
    #关闭shelfFile
    shelfFile.close()
    #打开shelfFile
    shelfFile = shelve.open('mydata')
    #打印shelfFile值
    print(shelfFile['cats'])
    

      运行结果:

      要利用shelve模块读写数据,首先要导入它。调用函数shelve.open()并传入一个文件名,然后将返回的值保存在一个变量中。可以对这个变量的 shelf 值进行修改,

    就像它是一个字典一样。当你完成时,在这个值上调用close()。这里,我们的shelf值保存在shelfFile中。我们创建了一个列表cats,并写下shelfFile['cats'] =cats,将该

    列表保存在shelfFile 中,作为键'cats'关联的值(就像在字典中一样)。然后我们在shelfFile上调用close()。

      在 Windows 上运行前面的代码,你会看到在当前工作目录下有 3 个新文件:mydata.bak、mydata.dat 和 mydata.dir。在 OS X 上,只会创建一个 mydata.db 文件。

    这些二进制文件包含了存储在 shelf 中的数据。这些二进制文件的格式并不重要,你只需要知道 shelve 模块做了什么,而不必知道它是怎么做的。该模块让你不用操心如

    何将程序的数据保存到文件中。

      2、就像字典一样,shelf 值有 keys()和 values()方法,返回 shelf 中键和值的类似列148 Python 编程快速上手——让繁琐工作自动化表的值。因为这些方法返回类似

    列表的值,而不是真正的列表,所以应该将它们传递给 list()函数,取得列表的形式。

      shelf的键-值,示例代码:

    # -*- coding:utf-8 -*-
    # Autor: Li Rong Yang
    import shelve,os
    #使用shelve.open(),打开一个文本文件
    shelfFile = shelve.open('mydata')
    #定义初始化数据列表
    cats = ['Zophie', 'Pooka', 'Simon']
    #把初始化列表赋给shelfFile
    shelfFile['cats'] = cats
    #关闭shelfFile
    shelfFile.close()
    #打开shelfFile
    shelfFile = shelve.open('mydata')
    #打印shelfFile的keys
    print(list(shelfFile.keys()))
    #打印shelfFile的values
    print(list(shelfFile.values()))
    

      运行结果:

      未填写keys或values的话默认是keys

      

  • 相关阅读:
    poj3686 Windys
    poj3155 Hard Life
    luoguP2774 方格取数问题
    poj3469 Dual Core CPU
    poj3281 Dining
    luogu P3410 拍照
    离散化
    最短路(SPFA)
    lower_bound && upper_bound
    gcd
  • 原文地址:https://www.cnblogs.com/lirongyang/p/9613891.html
Copyright © 2020-2023  润新知