I am trying to print all of the logged-in users tasks from a file(tasks.txt). This is what I have so far but it only prints out one task.
elif choice == "vm":
for task in taskList:
taskItems = task.split(":")
if loginUsername.strip() == taskItems[0].strip():
print(taskItems)
tasks.txt:
Shaun, Admin, Filing, 2020/4/09, 15/4/2020, No
Ashraf, Operations, Quote new air-condition, 2020/3/09, 10/4/2020, No
Clayton, IT, Finish Project, 2020/4/03, 30/4/2020, No
Shaun, Admin, Emails, 2020/4/07, 12/4/2020, No
Shaun, Admin, Data Captures, 2020/4/09, 13/4/2020, No
Roland, Marketing, Marketing Update, 2020/4/01, 10/4/2020, No
Therlow, Sales, Print New Leads, 2020/4/02, 4/4/2020, No
Shaun, Admin, Reply to Lerintha via email, 16/4/2020, 2020/04/15, No
Toni, Deliveries, Deliver all stock, 17/4/2020, 2020/04/16, No
Like SteveK, I assumed that you user name is in the first and the task in the third column:
with open ('tasks.txt', 'r') as f:
lines = f.readlines()
userTasks = dict()
for line in lines:
try:
user = line.split(',')[0].strip()
task = line.split(',')[2].strip()
userTasks.setdefault(user, []).append(task)
except IndexError:
continue
for user in userTasks:
print('{}: {}'.format(user, userTasks[user]))
Produces this output:
Shaun: ['Filing', 'Emails', 'Data Captures', 'Reply to Lerintha via email']
Ashraf: ['Quote new air-condition']
Clayton: ['Finish Project']
Roland: ['Marketing Update']
Therlow: ['Print New Leads']
Toni: ['Deliver all stock']
Added try
and except
to account for invalid lines
OP is looking for the complete lines from tasks.txt:
with open ('tasks.txt', 'r') as f:
lines = f.readlines()
loginUsername = 'Shaun'
userTasks = [line for line in lines if line.lstrip().startswith(loginUsername)]
print(''.join(userTasks))
Produces this output:
Shaun, Admin, Filing, 2020/4/09, 15/4/2020, No
Shaun, Admin, Emails, 2020/4/07, 12/4/2020, No
Shaun, Admin, Data Captures, 2020/4/09, 13/4/2020, No
Shaun, Admin, Reply to Lerintha via email, 16/4/2020, 2020/04/15, No