• python之shelve模块


    1、shevle简介

      利用 shelve 模块, 你可以将 Python 程序中的变量保存到二进制的 shelf 文件中。这样, 程序就可以从硬盘中恢复变量的数据。 shelve 模块让你在程序中添加“保存”和“打开” 功能。例如, 如果运行一个程序,并输入了一些配置设置,就可以将这些设置保存到一个 shelf 文件,然后让程序下一次运行时加载它们。

    2、方法

    2.1、写入数据

    import shelve
    import datetime
    d = shelve.open('shelve_test')  
    cats = ["Zophie", "Pooka", "Simon"]
    d["cats"] = cats
    d['date'] = datetime.datetime.now()
    d.close()

    2.2、读取数据

    import shelve
    d = shelve.open("shelve_test") # 打开一个文件
    print(d["cats"])
    print(d["date"])

    3、实例

    import shelve
    d = shelve.open("shelve_data") # open -- file may get suffix added by low-level library
    
    key = "you"
    data = 250
    
    d[key] = 250 # store data at key (overwrites old data if using an existing key)
    data = d[key] # retrieve a COPY of data at key (raise KeyError if no such key)
    del d[key] # delete data stored at key (raises KeyError if no such key)
    flag = key in d # true if the key exists
    klist = list(d.keys()) # a list of all existing keys (slow!)
    
    # as d was opened WITHOUT writeback=True, beware:
    d['xx'] = [0, 1, 2] # this works as expected, but...
    d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
    
    # having opened d without writeback=True, you need to code carefully:
    temp = d['xx'] # extracts the copy
    temp.append(5) # mutates the copy
    d['xx'] = temp # stores the copy right back, to persist it
    
    # or, d=shelve.open(filename,writeback=True) would let you just code
    # d['xx'].append(5) and have it work as expected, BUT it would also
    # consume more memory and make the d.close() operation slower.
    d.close()
  • 相关阅读:
    彩票股票金融与运气之研究(四)易道
    寻物一例
    彩票股票金融与运气之研究(三) 抽象模型
    彩票股票金融与运气之研究(一)前奏
    占何时可招到人
    占这单项目可成否
    C#控制DataMax打印机问题总结
    微软宣布Silverlight 5
    Windows Phone 7应用之sina微博——UI设计
    传言:Windows Phone 7“芒果”更新将增加 HTML5 支持
  • 原文地址:https://www.cnblogs.com/bad-robot/p/9734449.html
Copyright © 2020-2023  润新知