feat(python进阶): 新增进阶综合项目课程
This commit is contained in:
33
02_python进阶/2_9_python进阶综合项目/task_store.py
Normal file
33
02_python进阶/2_9_python进阶综合项目/task_store.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# 第 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")
|
||||
Reference in New Issue
Block a user