Files
PythonLearn/02_python进阶/2_9_python进阶综合项目/task_store.py
2026-08-10 17:26:38 +08:00

34 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 2-9 课完整示例:任务数据读写模块
#
# 本模块只负责把任务列表保存到文件,或从文件读取任务列表。
import json
from pathlib import Path
def load_tasks(data_file: Path) -> list[dict[str, object]]:
"""从 JSON 文件读取任务列表;文件不存在或内容有误时返回空列表。"""
if not data_file.exists():
return []
try:
content = data_file.read_text(encoding="utf-8")
tasks = json.loads(content)
except (OSError, json.JSONDecodeError):
# 读取失败或 JSON 格式不正确时,给出安全的空列表,避免程序崩溃。
return []
# JSON 可以保存多种数据。这里只接受列表,避免后续遍历时出现意外错误。
if not isinstance(tasks, list):
return []
return tasks
def save_tasks(data_file: Path, tasks: list[dict[str, object]]) -> None:
"""把任务列表保存为 UTF-8 编码的 JSON 文件。"""
# 父目录不存在时先创建exist_ok=True 允许程序重复运行。
data_file.parent.mkdir(parents=True, exist_ok=True)
content = json.dumps(tasks, ensure_ascii=False, indent=2)
data_file.write_text(content, encoding="utf-8")