-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.py
More file actions
executable file
·100 lines (84 loc) · 2.88 KB
/
todo.py
File metadata and controls
executable file
·100 lines (84 loc) · 2.88 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
96
97
98
99
100
#!/usr/bin/env python3
''' Command line TODO tool that stores a list of tasks in ~/.todo.txt that
is manipulated via a(dd), d(elete) and l(ist) arguments. Supply -h or
--help for usage information
'''
import os
import sys
def print_usage():
''' print program usage '''
usage = ' '.join(('\nUsage: todo.py [-adh] "text to add"',
'\n\ta "text to add # add task',
'\n\td <number> # delete task'
'\n\tl (or no argument) # list tasks\n'))
return usage
def handle_arguments(fname, args):
''' simple argument handling '''
if len(args) == 1: # no args, list tasks
print_list(read_file(fname))
return
if args[1] == '-h' or args[1] == '--help':
print(print_usage())
return
if args[1] == 'l' or args[1] == 'list': # list all
print_list(read_file(fname))
if args[1] == 'a' or args[1] == 'add': # add entry
print(add_entry(fname, args[2:]))
if args[1] == 'd' or args[1] == 'del': # remove entry
msg = delete_entry(fname, args[2])
if msg:
print(msg)
return
def read_file(fname):
''' read TODO file and print contents '''
messages = []
if os.path.isfile(fname):
with open(fname,'r', encoding='UTF-8') as fhandle:
entries = fhandle.read().splitlines()
for count, msg in enumerate(entries, start=1):
messages.append('%3d %s' % (count, msg))
if len(messages) > 0:
return messages
return ['<empty list>']
def add_entry(fname, msg):
''' add a new item to TODO list '''
entry = ' '.join(msg)
mode = 'w'
if os.path.isfile(fname):
mode = 'a'
with open(fname, mode, encoding='UTF-8') as fhandle:
fhandle.write(entry + '\n')
return f'Added: {entry}'
def delete_entry(fname, number):
''' remove item from TODO list '''
new_todos = []
if number.isnumeric():
number = int(number)
if os.path.isfile(fname):
with open(fname, 'r', encoding='UTF-8') as fhandle:
entries = fhandle.read().splitlines()
for count, msg in enumerate(entries, start=1):
if count == number:
return_msg = f'Removed {msg}'
else:
new_todos.append(msg)
if new_todos:
with open(fname, 'w', encoding='UTF-8') as fhandle:
for msg in new_todos:
fhandle.write(msg + '\n')
else:
os.remove(fname)
else:
return_msg = '-- Not a line number --'
return return_msg
def print_list(msg):
''' pretty print list '''
for line in msg:
print(line)
def main():
''' program main function '''
fname = '~/.todo.txt'
fname = os.path.expanduser(fname)
handle_arguments(fname, sys.argv)
if __name__ == "__main__":
main()