Skip to content

Commit 39c9397

Browse files
authored
Merge pull request #385 from buffaloist/20240511
rewrite to clean up code, use argparser, utilize functions, set variables for file paths
2 parents a946734 + 9a9136b commit 39c9397

File tree

3 files changed

+139
-111
lines changed

3 files changed

+139
-111
lines changed

PYTHON APPS/CLI-Based-TODO/task.py

100644100755
+139-111
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,145 @@
1-
import time,os,sys
1+
#!/usr/bin/env python3
2+
# Python todo list
23

3-
usage = "Usage :-\n$ ./task add 2 'hello world' # Add a new item with priority 2 and text \"hello world\" to the list\n$ ./task ls # Show incomplete priority list items sorted by priority in ascending order\n$ ./task del INDEX # Delete the incomplete item with the given index\n$ ./task done INDEX # Mark the incomplete item with the given index as complete\n$ ./task help # Show usage\n$ ./task report # Statistics ( list complete/incomplete task )"
4-
5-
def func():
6-
try:
7-
8-
# printing help
9-
if sys.argv[1]=="help":
10-
print(usage)
11-
return usage
12-
13-
# lisiting all the task
14-
if sys.argv[1]=="ls":
15-
try:
16-
f = open("path/to/plans/task.txt",'r')
17-
data = f.read()
18-
datalist = data.split("\n")
19-
datalist = sorted(datalist)
20-
datalist = datalist[1:]
21-
# print(datalist)
22-
for i in range(len(datalist)):
23-
print(f"{i+1}. {datalist[i][2:]} [{datalist[i][0:1]}]")
24-
25-
except:
26-
print("Error: Missing file")
4+
import os
5+
from argparse import ArgumentParser as aparse
276

7+
# change the path of the files here to the actual desired paths
8+
taskTxt = "task.txt"
9+
completedTxt = "completed.txt"
2810

11+
def create_parser():
12+
parser = aparse(description="""Command Line task list""")
13+
parser.add_argument("toDo", default="ls", choices=['usage', 'ls', 'add', 'del', 'done', 'report'], help="Enter command: usage, ls, add, del, done, report.")
14+
parser.add_argument("-p", required=False, type=int, help="item priority")
15+
parser.add_argument("-i", required=False, type=str, help="List item to add, remove, or mark done.")
16+
return parser
2917

30-
# adding the task
31-
if sys.argv[1]=="add":
32-
try:
33-
with open("path/to/plans/task.txt",'a',encoding = 'utf-8') as f:
34-
res = f.write(f"{sys.argv[2]} {sys.argv[3]}\n")
35-
except:
36-
print("Error: Missing tasks string. Nothing added!")
37-
else:
38-
print(f"Added task: \"{sys.argv[3]}\" with priority {sys.argv[2]}")
39-
40-
41-
42-
# deleting the task
43-
if sys.argv[1]=="del":
44-
lineno = int(sys.argv[2])
45-
try:
46-
with open("path/to/plans/task.txt","r+") as f:
47-
new_f = f.readlines()
48-
new_f = sorted(new_f)
49-
# print(new_f)
50-
del_f = new_f.pop(lineno-1)
51-
# print(new_f)
52-
53-
f.seek(0)
54-
for line in new_f:
55-
if del_f not in line:
56-
f.write(line)
57-
f.truncate()
58-
except:
59-
print(f"Error: item with index {lineno} does not exist. Nothing deleted.")
60-
61-
62-
63-
# marking done
64-
if sys.argv[1]=="done":
65-
lineno = int(sys.argv[2])
18+
def func():
19+
args = create_parser().parse_args()
20+
21+
# check if files exist, create if not
22+
if not os.path.exists(taskTxt):
23+
with open(taskTxt, "w") as filet:
24+
pass
25+
26+
if not os.path.exists(completedTxt):
27+
with open(completedTxt, "w") as filec:
28+
pass
29+
30+
if args.toDo == "ls":
31+
lister(read_list())
32+
33+
# adding the task
34+
if args.toDo == "add":
35+
if args.i == '' or args.p == '':
36+
raise ValueError('An item and priority must be entered')
37+
taskList = read_list()
38+
taskList.insert((args.p - 1), args.i)
39+
with open(taskTxt, "w") as f:
40+
for line in taskList:
41+
f.write(line + "\n")
42+
43+
44+
# deleting the task
45+
if args.toDo == "del":
46+
if args.i == '' or args.p == '':
47+
raise ValueError('An item or priority must be entered')
48+
taskList = read_list()
49+
if args.p:
50+
index = args.p - 1
51+
delete_item(index, taskList)
52+
else:
6653
try:
67-
with open("path/to/plans/task.txt","r+") as f:
68-
new_f = f.readlines()
69-
new_f = sorted(new_f)
70-
# print(new_f)
71-
del_f = new_f.pop(lineno-1)
72-
# print(new_f)
73-
74-
f.seek(0)
75-
for line in new_f:
76-
if del_f not in line:
77-
f.write(line)
78-
with open("path/to/plans/completed.txt","a") as r:
79-
r.write(del_f)
80-
f.truncate()
81-
82-
83-
84-
except:
85-
print(f"Error: no incomplete item with index #0 exists.")
86-
else:
87-
print(f"Marked item as done.")
88-
89-
90-
# generating the report
91-
if sys.argv[1]=="report":
54+
index = taskList.index(args.i)
55+
delete_item(index, taskList)
56+
exit(0)
57+
except(ValueError):
58+
print(f"Item {args.i} not found. Maybe run ls and try again?")
59+
exit(0)
60+
61+
# marking done
62+
if args.toDo == "done":
63+
if args.i == '' or args.p == '':
64+
raise ValueError('An item or priority must be entered')
65+
taskList = read_list()
66+
if args.p:
67+
index = args.p - 1
68+
do_item(index, taskList)
69+
else:
9270
try:
93-
task = open("path/to/plans/task.txt",'r')
94-
data = task.read()
95-
datalist = data.split("\n")
96-
datalist = sorted(datalist)
97-
datalist = datalist[1:]
98-
print(f"Pending : {len(datalist)}")
99-
for i in range(len(datalist)):
100-
print(f"{i+1}. {datalist[i][2:]} [{datalist[i][0:1]}]")
101-
102-
compt = open("path/to/plans/completed.txt",'r')
103-
data = compt.read()
104-
datalist = data.split("\n")
105-
datalist = sorted(datalist)
106-
datalist = datalist[1:]
107-
print(f"Completed : {len(datalist)}")
108-
for i in range(len(datalist)):
109-
print(f"{i+1}. {datalist[i][2:]} [{datalist[i][0:1]}]")
110-
except:
111-
print("Error: Missing file")
112-
113-
except:
114-
print(usage)
115-
return usage.encode('utf8')
116-
117-
func()
71+
index = taskList.index(args.i)
72+
do_item(index, taskList)
73+
exit(0)
74+
except(ValueError):
75+
print(f"Item {args.i} not found. Maybe run ls and try again?")
76+
exit(0)
77+
78+
# generating the report
79+
if args.toDo == "report":
80+
print("\n")
81+
print("To do:")
82+
lister(read_list())
83+
print("\n")
84+
print("Done:")
85+
lister(read_complete())
86+
87+
def read_list():
88+
with open(taskTxt, "r") as file:
89+
task_list = file.readlines()
90+
# all the newlines added during file writing must be removed otherwise printing is messed up
91+
strip_list = []
92+
for item in task_list:
93+
strip_list.append(item.strip())
94+
filtered_list = [item for item in strip_list if item != ""]
95+
return filtered_list
96+
97+
def read_complete():
98+
with open(completedTxt, "r") as file:
99+
completed_list = file.readlines()
100+
# all the newlines added during file writing must be removed otherwise printing is messed up
101+
strip_list = []
102+
for item in completed_list:
103+
strip_list.append(item.strip())
104+
filtered_list = [item for item in strip_list if item != ""]
105+
return filtered_list
106+
107+
def delete_item(index, taskList):
108+
print("\n")
109+
print(f"Do you want to delete {taskList[index]}?")
110+
answer = input("Enter y or n: ")
111+
if answer == "y":
112+
taskList.pop(index)
113+
with open(taskTxt, "w") as f:
114+
for line in taskList:
115+
f.write(line + "\n")
116+
print("Item Deleted")
117+
exit(0)
118+
print("No item deleted")
119+
exit(0)
120+
121+
def do_item(index, taskList):
122+
print("\n")
123+
print(f"Do you want to move {taskList[index]} to done?")
124+
answer = input("Enter y or n: ")
125+
if answer == "y":
126+
task = taskList.pop(index)
127+
with open(taskTxt, "w") as f:
128+
for line in taskList:
129+
f.write(line + "\n")
130+
completed = read_complete()
131+
completed.append(task)
132+
with open(completedTxt, "w") as f:
133+
for line in completed:
134+
f.write(line + "\n")
135+
print("Item marked done")
136+
exit(0)
137+
print("No item changed")
138+
exit(0)
139+
140+
def lister(items):
141+
for item, line in enumerate(items, 1):
142+
print(f"{item}: {line.strip()}")
143+
144+
if __name__ == "__main__":
145+
func()

PYTHON APPS/CLI-Based-TODO/time,os,sys

Whitespace-only changes.

file.txt

Whitespace-only changes.

0 commit comments

Comments
 (0)