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    
2

There are 2 best solutions below

21
Stefan Scheller On BEST ANSWER

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']

Update 1:

Added try and except to account for invalid lines

Update 2:

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
0
SteveK On

Since you're working with comma-separated values, you can read tasks.txt as a CSV file. This assumes the usernames are always in the 1st column and tasks in the 3rd column (Filing, Finish Project, etc.)

import csv
with open('tasks.txt') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        if loginUsername.strip() == row[0].strip():
            print(row[2])

This approach removes the explicit call to split(',') as commas are the default delimiter for csv_reader().