forked from Macha/Simple-Python-Todo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodolist.py
130 lines (106 loc) · 2.42 KB
/
todolist.py
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import json
class NoSuchListError(Exception): pass
class TodoList:
"""
Contains the code needed to manage the todo list.
"""
def __init__(self, json_location):
"""
Sets up the list.
"""
self.json_location = json_location
self.load()
def add(self, text):
"""
Adds an item to the list
"""
try:
last_id = self.list[-1].id
except IndexError:
# No items in list
last_id = - 1
new_item = TodoItem(last_id + 1, text)
self.list.append(new_item)
return new_item
def __str__(self):
stringlist = []
for item in self.list:
stringlist.append(str(item.id) + '\t' + str(item.text))
string = '\n'.join(stringlist)
return string
def idLessString(self):
"""
Returns a string of this list without the id numbers.
"""
string = ''
for item in self.list:
string = string + str(item.text) + '\n'
string = string[:-1] # Cut out final newline
return string
def __len__(self):
return len(self.list)
def __iter__(self):
return self.forward()
def __getitem__(self, item_id):
print item_id
for todo in self.list:
if todo.id == item_id:
return todo
else:
print item_id, 'not matched for', todo.id, todo
raise IndexError('No such item')
def forward(self):
current_item = 0
while (current_item < len(self)):
item = self.list[current_item]
current_item += 1
yield item
def __contains__(self, item):
if item in self.list:
return True
return False
def remove(self, item_id):
"""
Removes an item from the list.
"""
todo = self[item_id]
removed_text = todo.text
self.list.remove(todo)
return removed_text
def load(self):
"""
Loads the list data from file.
"""
try:
json_file = open(self.json_location, 'r')
json_text = json_file.read()
json_file.close()
json_list = json.loads(json_text)
self.list = []
for item in json_list:
self.list.append(TodoItem(item['id'], item['text']))
print item
except IOError:
raise NoSuchListError
def save(self):
"""
Writes the list data to file.
"""
json_file = open(self.json_location, 'w')
json_list = []
# Re-order indices
id = 0
for item in self.list:
item.id = id
json_list.append(item.asdict())
id += 1
json_file.write(json.dumps(json_list))
json_file.close()
class TodoItem:
def __init__(self, id, text):
self.id = id
self.text = text
def __str__(self):
return self.text
def asdict(self):
return {'id': self.id, 'text': self.text }