-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo_manager.py
More file actions
95 lines (71 loc) · 2.55 KB
/
Copy pathtodo_manager.py
File metadata and controls
95 lines (71 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import json
import os
class Task:
"""Represents a single task in the to-do list."""
def __init__(self, title, completed=False):
self.title = title
self.completed = completed
def to_dict(self):
"""Convert the task into a dictionary for JSON storage."""
return {
"title": self.title,
"completed": self.completed
}
@classmethod
def from_dict(cls, data):
"""Create a Task object from stored JSON data."""
return cls(
data["title"],
data.get("completed", False)
)
class TodoManager:
"""Manages tasks and handles saving/loading task data."""
def __init__(self, filename="tasks.json"):
self.filename = filename
self.tasks = []
self.load_tasks()
def add_task(self, title):
"""Add a new task to the list."""
title = title.strip()
if not title:
raise ValueError("Task description cannot be empty.")
self.tasks.append(Task(title))
self.save_tasks()
def view_tasks(self):
"""Return all tasks."""
return self.tasks
def complete_task(self, task_number):
"""Mark a selected task as completed."""
index = task_number - 1
if index < 0 or index >= len(self.tasks):
raise IndexError("Invalid task number.")
self.tasks[index].completed = True
self.save_tasks()
def remove_task(self, task_number):
"""Remove a selected task."""
index = task_number - 1
if index < 0 or index >= len(self.tasks):
raise IndexError("Invalid task number.")
removed_task = self.tasks.pop(index)
self.save_tasks()
return removed_task
def save_tasks(self):
"""Save all tasks to a JSON file."""
with open(self.filename, "w", encoding="utf-8") as file:
json.dump(
[task.to_dict() for task in self.tasks],
file,
indent=4
)
def load_tasks(self):
"""Load tasks from the JSON file when the application starts."""
if not os.path.exists(self.filename):
return
try:
with open(self.filename, "r", encoding="utf-8") as file:
data = json.load(file)
self.tasks = [Task.from_dict(item) for item in data]
except (json.JSONDecodeError, KeyError, TypeError):
# If the storage file is damaged, start with an empty list
# instead of crashing the entire application.
self.tasks = []