83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
import json
|
|
import os
|
|
|
|
# 以下为 V1.0 原有代码,完全未修改
|
|
|
|
# 定义数据文件路径
|
|
HOUSE_FILE = "./data/houses.json"
|
|
|
|
def init_db():
|
|
"""
|
|
初始化数据文件:如果houses.json不存在,创建并写入空列表
|
|
空间复杂度:O(1)(仅创建空文件)
|
|
"""
|
|
# 确保data文件夹存在
|
|
os.makedirs("./data", exist_ok=True)
|
|
# 如果文件不存在,创建并写入空列表
|
|
if not os.path.exists(HOUSE_FILE):
|
|
with open(HOUSE_FILE, 'w', encoding='utf-8') as f:
|
|
json.dump([], f, ensure_ascii=False, indent=4)
|
|
|
|
def read_houses():
|
|
"""
|
|
读取所有房源数据
|
|
时间复杂度:O(n)(n为房源数,JSON解析耗时与数据量正相关)
|
|
空间复杂度:O(n)(存储所有房源数据)
|
|
return: 房源列表(每个元素是字典)
|
|
"""
|
|
init_db() # 先确保文件存在
|
|
with open(HOUSE_FILE, 'r', encoding='utf-8') as f:
|
|
return json.load(f)
|
|
|
|
def write_houses(houses):
|
|
"""
|
|
写入房源数据到JSON文件
|
|
时间复杂度:O(n)(n为房源数,JSON序列化耗时与数据量正相关)
|
|
空间复杂度:O(1)(仅写入操作,无额外存储)
|
|
param houses: 要写入的房源列表
|
|
"""
|
|
with open(HOUSE_FILE, 'w', encoding='utf-8') as f:
|
|
json.dump(houses, f, ensure_ascii=False, indent=4)
|
|
|
|
# V2.0 新增代码:栈数据读写
|
|
|
|
# V2.0 新增:栈数据文件配置
|
|
STACK_FILE = "./data/stack_data.json"
|
|
|
|
# V2.0 新增:栈数据初始化与读写
|
|
def init_stack_db():
|
|
"""
|
|
初始化栈数据文件:若不存在则创建,区分操作记录栈/浏览历史栈
|
|
"""
|
|
os.makedirs("./data", exist_ok=True)
|
|
if not os.path.exists(STACK_FILE):
|
|
init_data = {
|
|
"operation_stack": [],
|
|
"browse_stack": []
|
|
}
|
|
with open(STACK_FILE, 'w', encoding='utf-8') as f:
|
|
json.dump(init_data, f, ensure_ascii=False, indent=4)
|
|
|
|
def read_stack(stack_type):
|
|
"""
|
|
读取指定类型的栈数据
|
|
:param stack_type: operation(操作记录)/ browse(浏览历史)
|
|
"""
|
|
init_stack_db()
|
|
with open(STACK_FILE, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
stack_key = f"{stack_type}_stack"
|
|
return data.get(stack_key, [])
|
|
|
|
def write_stack(stack_type, new_stack):
|
|
"""
|
|
写入指定类型的栈数据到文件
|
|
"""
|
|
init_stack_db()
|
|
# 读取原有数据,避免覆盖另一个栈
|
|
with open(STACK_FILE, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
stack_key = f"{stack_type}_stack"
|
|
data[stack_key] = new_stack
|
|
with open(STACK_FILE, 'w', encoding='utf-8') as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=4) |