0

谁能帮我将任务编号添加到我当前的代码中。我已经为用户编写了代码来为不同的用户添加任务,但现在我需要将任务编号添加到我的任务输出文本中。当前文本显示如下:

分配给任务的用户:
杰克

任务名称:

任务描述:

遛狗

任务截止日期:

2020-03-02

分配日期:

2020-02-05

任务完成:

现在我想要的只是输出如下:

分配给任务 1 的用户:

杰克

任务名称:

任务描述:

遛狗

任务截止日期:

2020-03-02

分配日期:

2020-02-05

任务完成:

并且还能够在用户请求时按编号显示特定任务。因此,如果任务编号完全可以调用,这将非常有帮助。

我当前的代码是:

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()

感谢您的任何帮助。

4

1 回答 1

0

对于初始文件上下文,例如:

task 1
description: something

您需要读取文件并找到最后一个任务编号。然后创建编号增加 1 的新任务并将其附加到文件中。

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)

输出:

task 1
description: something
task 2
description: something
task 3
description: something
于 2020-02-06T12:48:13.923 回答