一个基于 JSON 的键-值存储类。与操作 Python 字典类似,但每次修改后都会自动保存到硬盘
Project description
项目描述
WSS
是一个简单的基于 JSON 的键-值存储类。它提供了一种方便的方法来操作 JSON 文件,与操作 Python 字典类似,但每次修改后都会自动进行持久化。
安装
pip install wss
教程
初始化
首先,导入 WSS
类并初始化一个实例:
from WSS import WSS
store = WSS('path/to/your/file.json')
增加键
要增加一个键,只需像操作字典那样赋值:
store['new_key'] = 'new_value'
此操作将立即写入文件。
删除键
使用 pop
方法删除指定的键并返回其值:
removed_value = store.pop('key_to_remove')
如果指定的键不存在,pop
会抛出一个 KeyError
。如果你想避免这个错误并在键不存在时返回一个默认值,你可以这样做:
removed_value = store.pop('key_to_remove', default_value)
更新键
使用 update
方法一次更新多个键:
store.update({'key1': 'updated_value1', 'key2': 'updated_value2'})
或者你可以简单地为每个键分别赋值:
store['key1'] = 'updated_value1'
查询键
要查询键的值,只需像操作字典那样:
value = store['key_to_query']
如果该键不存在,此操作会抛出一个 KeyError
。为避免错误,你可以使用 get
方法:
value = store.get('key_to_query', 'default_value')
其他常用方法
-
获取所有的键、值或键值对:
keys = store.keys() values = store.values() items = store.items()
-
如果键不存在,则设置其默认值:
store.setdefault('absent_key', 'default_value')
如果键
absent_key
不存在于WSS
中,它将被添加,并赋予default_value
作为值。 -
合并两个
WSS
对象或字典:other_data = {'key5': 'value5'} store |= other_data
这将把
other_data
的内容合并到store
中,如果有任何重复的键,store
中的值将被other_data
中的值覆盖。 -
获取
WSS
对象中的项数:length = len(store)
-
迭代
WSS
对象中的键:for key in store: print(key)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
wss-1.0.tar.gz
(6.5 kB
view hashes)
Built Distribution
wss-1.0-py3-none-any.whl
(6.7 kB
view hashes)