Warm tip: This article is reproduced from stackoverflow.com, please click
external-data-source python task

Adding task numbers

发布于 2020-04-21 22:00:42

Could anyone help me adding task numbers to my current code. I've written code for users to add tasks for different users but now I need to add task numbers to my task output text. The current text is displaying as shown:

User assigned to task:
jake

Task Title:

walk

Task Description:

walk the dog

Task Due Date:

2020-03-02

Date Assigned:

2020-02-05

Task Completed:

No

Now all I would like is the output to be as:

User assigned to task 1:

jake

Task Title:

walk

Task Description:

walk the dog

Task Due Date:

2020-03-02

Date Assigned:

2020-02-05

Task Completed:

No

and also to be able to display a specific task by number if the user requests it. So if the task numbers are callable at all this would really help.

my current code is:

def add_task():
 if menu == "a" or menu == "A":
    with open( 'user.txt' ) as fin :    
        usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
        task = input ("Please enter the username of the person the task is assigned to.\n")
    while task not in usernames :
        task = input("Username not registered. Please enter a valid username.\n")
    else:
        task_title = input("Please enter the title of the task.\n")
        task_description = input("Please enter the task description.\n")
        task_due = input("Please input the due date of the task. (yyyy-mm-dd)\n")
        date = datetime.date.today()
        task_completed = False
        if task_completed == False:
            task_completed = "No"
        else:
            task_completed = ("Yes")
        with open('tasks.txt', 'a') as task1:
            task1.write("\nUser assigned to task:\n" + task + "\nTask Title :"  + "\n" + task_title + "\n" + "Task Description:\n" + task_description + "\n" + "Task Due Date:\n" + task_due + "\n" + "Date Assigned:\n" + str(date) + "\n" + "Task Completed:\n" + task_completed + "\n")
            print("The new assigned task has been saved")
add_task()

Thank you for any help.

Questioner
user12739323
Viewed
48
Zaraki Kenpachi 2020-02-06 20:48

For initial file context like:

task 1
description: something

You need read file and find last task number. Then create new task with number increased by 1 and append that to the file.

import re

data = open('test.txt', 'r')
listed_data = data.readlines()

# get last task number
last_task = [line for line in listed_data if 'task' in line][-1]
current_task_number = int(re.findall('\d+', last_task)[0])


# add new task with new number
def add_task(number):
    file = open('test.txt', 'a')
    file.write('task ' + str(number+1) + '\n')
    file.write('description: ' + str('something') + '\n')
    file.close()

add_task(current_task_number)

Output:

task 1
description: something
task 2
description: something
task 3
description: something