zoukankan      html  css  js  c++  java
  • 🍖shelve 模块

    一. 什么是 shelve 模块

    • shelve 模块也是 Python 提供给我们的序列化工具
    • shelvepickle 用起来简单一些

    二.使用方法

    • 使用时, 只需要使用 open 函数获取一个 shelf 对象 (类似字典)
    • 可以将shelf对象看做一个字典来存储数据 (key 必须为字符串, 值可以是Python所支持的数据类型)
    • 然后对数据进行增删改查, 操作完成后, 将内容从内存刷到磁盘中, 最后调用 close 函数关闭文件

    三.使用示例

    1.保存数据

    import shelve,datetime
    
    f = shelve.open(r"./ttt.txt")  # 这个文件是shelve生成的,不能已存在, 不然格式与shelve不符,将报错
    f["user_info"]  = {"name":"shawn","age":18}
    f["hobby_list"] = ["read","sleep","run","eat"]
    f["time_now"] = datetime.datetime.now()
    
    f.close()
    

    2.获取数据 (演示多种取值方法)

    import shelve
    
    f = shelve.open(r"./ttt.txt")
    
    print(f.get("user_info"))  # {'name': 'shawn', 'age': 18}
    print(f.get("hobby_list")) # ['read', 'sleep', 'run', 'eat']
    print(f.get("time_now"))   # 2020-12-21 12:18:42.300267
    
    print(f["user_info"])      # {'name': 'shawn', 'age': 18}
    print(f["hobby_list"])     # ['read', 'sleep', 'run', 'eat']
    print(f["time_now"])       # 2020-12-21 12:18:42.300267
    
    print(f["user_info"]["name"])     # shawn
    print(f["hobby_list"][1])         # sleep
    print(f.get("user_info")["age"])  # 18
    print(f.get("hobby_list")[0])     # read
    
    f.close()
    
  • 相关阅读:
    linux上安装vsftpd
    springboot集成mybatisplus
    springboot集成swagger2
    ssm+maven多模块项目整合
    追梦强人工智能(一)
    Linux环境kafka安装
    Linux环境安装jdk10
    东芝笔记本Satellite M40-A
    Maven简介
    postgresql PL/pgSQL—存储过程结构和变量声明
  • 原文地址:https://www.cnblogs.com/songhaixing/p/14167301.html
Copyright © 2011-2022 走看看