简体   繁体   中英

using a for loop to read an external file in python and my else statement prints more than once, I need to find a way to change this

So for context I have two files: and external file called tasks.txt and my main file called task_manager.py. The format of tasks.txt is like this:

admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No

Note that this is all one line. To break this down it starts with the username and then separated by a comma and a space its the task title and the the task description and then the date assigned then the date due and finally whether the task is complete or not.

Now my job is to read this external file and print a set format of each line depending on if the username matches that of the ones in the file. I have managed to do this first bit however when the username does not match I want to display a message saying "You have no tasks at the moment". the problem is since it is a for loop it repeats this message for every line in the tasks.txt file.

This is the code I've written:

username = "admi"

f2 = open('tasks.txt', 'r')

for line in f2:
    line3_split = line.split(', ')
    if line3_split[0] == username:
        user_format = f"""
        Task:              {line3_split[1]}
        Assigned to:       {line3_split[0]}
        Date assigned:     {line3_split[3]}
        Due date:          {line3_split[4]}
        Task complete?     {line3_split[5]}
        Task description:  
         {line3_split[2]}
        """
        print(user_format)
    else:
        print("You have no tasks at the moment.")


f2.close()

There might be a simple answer to this but my head is scrambled lol.

UPDATE:

So I have changed my code to this

username = "admn"

f2 = open('tasks.txt', 'r')

is_user = f2.read()

if username in is_user:
    for line in f2:
        line3_split = line.split(', ')
        if line3_split[0] == username:
            user_format = f"""
            Task:              {line3_split[1]}
            Assigned to:       {line3_split[0]}
            Date assigned:     {line3_split[3]}
            Due date:          {line3_split[4]}
            Task complete?     {line3_split[5]}
            Task description:  
            {line3_split[2]}
            """
            print(user_format)
else:
    print("You have no tasks at the moment.")

f2.close()

This solves my initial problem however this time the for loop doesn't work. Is it that once the external file is read once then it can't be read again? Is there a solution to this?

Final update!

Ive managed to solve this problem using.seek() to be able to reread the external file. My final code is as follows:

username = "admin"

f2 = open('tasks.txt', 'r')

is_user = f2.read()

if username in is_user:
    f2.seek(0,0)
    for line in f2:
        line3_split = line.split(', ')
        if line3_split[0] == username:
            user_format = f"""
            Task:              {line3_split[1]}
            Assigned to:       {line3_split[0]}
            Date assigned:     {line3_split[3]}
            Due date:          {line3_split[4]}
            Task complete?     {line3_split[5]}
            Task description:  
             {line3_split[2]}
            """
            print(user_format)
else:
    print("You have no tasks at the moment.")

f2.close()

I see two solutions possible.

First, you can read the file, put all the data in an array of map (dict in python) and go through this array.

Or, you can do like Tim said, and set a flag.

Here is code for both of those idea:

Array of dict:

username = "admi"

f2 = open('tasks.txt', 'r')

tasks = []

for line in f2:
    line3_split = line.split(',')

    this_task = {
        "task": line3_split[1],
        "assigned_to": line3_split[0],
        "date_assigned": line3_split[3],
        "due_date": line3_split[4],
        "task_complete": line3_split[5],
        "task_description": line3_split[2]
    }

    tasks.append(this_task)
f2.close()


if not any(d["assigned_to"] == username for d in tasks):
    print("You have no tasks at the moment.")
else:
    for task in tasks:
        if task["assigned_to"] == username:
            user_format = f"""
            Task:              {task["task"]}
            Assigned to:       {task["assigned_to"]}
            Date assigned:     {task["date_assigned"]}
            Due date:          {task["due_date"]}
            Task complete?     {task["task_complete"]}
            Task description:  
                {task["task_description"]}
            """
            print(user_format)

Flag:

username = "admi"

f2 = open('tasks.txt', 'r')

no_task = True
for line in f2:
    line3_split = line.split(',')
    if line3_split[0] == username:
        no_task = False
        user_format = f"""
        Task:              {line3_split[1]}
        Assigned to:       {line3_split[0]}
        Date assigned:     {line3_split[3]}
        Due date:          {line3_split[4]}
        Task complete?     {line3_split[5]}
        Task description:  
         {line3_split[2]}
        """
        print(user_format)

if no_task:
    print("You have no tasks at the moment.")


f2.close()

I tried these two files with this tasks.txt and it worked:

me,task1,description,20/20/20,21/21/21,True
admi,task3,description,20/20/20,21/21/21,False
albert,task2,description,20/20/20,21/21/21,False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM