Python,定义函数以生成从任务管理器程序跟踪的多个 txt 文件?

Python, define functions to generate multiple txt files tracked from task manager program?

我有一个任务需要从 .txt 文件读取、写入和显示信息的函数。
我已经完成了代码的第一部分。

我正在努力弄清楚这部分问题:

1.在应用程序的主菜单中添加生成报告的选项。
管理员用户的菜单现在应该如下所示:

Please select on of the following options:  
r - register user  
a - add task  
va- view all tasks  
vm - view my tasks  
gr - generate reports  
ds - display statistics  
e - exit  

上面的菜单我已经装箱了

2. 当用户选择生成报告时,两个文本文件,分别叫做task_overview.txtuser_overview.txt,应该生成。这两个文本文件都应以用户友好、易于阅读的方式输出数据。

2.1 task_overview.txt 应包含:
使用任务管理器.
生成和跟踪的任务总数 完成任务总数。
未完成任务总数。
未完成和逾期的任务总数。
未完成任务的百分比。
逾期任务的百分比。

2.2 user_overview.txt 应包含:
使用任务管理器.
注册的用户总数 使用任务管理器.

生成和跟踪的任务总数

对于每个用户还描述:
分配给该用户的任务总数。
分配给该用户的任务占总任务数的百分比是多少?
分配给该用户的任务的完成百分比是多少?
分配给该用户的任务中有多少百分比仍必须完成?
分配给该用户的任务中有多少百分比尚未完成且已逾期?

3.修改允许管理员显示统计信息的菜单选项,以便从task_overview.txt[=78=读取生成的报告] 和 user_overview.txt 并以用户友好的方式显示在屏幕上。

任何指导都会非常有用

这是我的任务管理器到目前为止的代码:
请参阅 def reports(): and def statistics(): 在代码中

更新: 根据“RolvApneseth”的建议缩短了原始 post 的代码量

    def reports():   # NOTE: these are the functions I need help with please.
    
        return
    
    def statistics():   # NOTE: these are the functions I need help with please.
    
        return


    def displayMenu_Admin():
    
        global menu_input
    
        menu_input = input("""
    Please enter one of the following options:
    r - register user
    a - add task
    va- view all tasks
    vm - view my tasks
    gr - generate reports
    ds - display statistics
    e - exit
    """)

    if menu_input == "r":
        register()
    elif menu_input == "a":
        add_task()
    elif menu_input == "va":
        view_all()
    elif menu_input == "vm":
        view_more()
    elif menu_input == "gr":
        reports()
    elif menu_input == "ds":
        statistics() 
    elif menu_input == "e":
        exit()

    return menu_input


    #A menu should be displayed once the user has successfully logged in.
    
    def displayMenu():
    
        global menu_input
    
        menu_input = input("""
    Please enter one of the following options:
    a - add task
    va- view all tasks
    vm - view my tasks
    e - exit
    """)
    
        if menu_input == "a":
            add_task()
        elif menu_input == "va":
            view_all()
        elif menu_input == "vm":
            view_more()
        elif menu_input == "e":
            exit()
    
        return menu_input

    
    def login():
    
        username = input("Please enter your username?:\n")
        password = input("Please enter your password?:\n")
    
        for line in open("user.txt","r").readlines():
            field = line.strip().split(", ")
            if username == field[0] and password == field[1]:
                print("Hello " + username + ", welcome back!\n")
                return True, field[0]== "admin"
    
        return False, False
    
    login_success, is_admin = login()
    
    if login_success and is_admin:
       displayMenu_Admin()
    elif login_success:
       displayMenu()
    else:
       print("Username or Password Incorrect\n")

我最终不得不更改原始代码的某些部分,但最终在一些帮助下,我得到了我正在寻找的函数的答案...
希望这对以后的其他人有所帮助!


# Displaying only admin specific statistics to the screen.
def display_admin_stats():

    # exists(), it says that there are specific cases in which a file or folder exists but,
    # 'os.path.exists()' returns false: Return True if path refers to an existing path or an open file descriptor.
    if not os.path.exists('task_overview.txt') and not os.path.exists('user_overview.txt'):

        generate_task_overview() # Calls the function that generates 'task_overview.txt'.
        generate_user_overview() # Calls the function that generates 'user_overview.txt'.
    
    print("Displaying statistics for admin:\n")
    user_dictionary = user_dict()
    task_dictionary = task_dict()
    
    print(f"Total number of tasks: {len(task_dictionary)}")
    print(f"Total number of users: {len(user_dictionary)}")
            
    with open('task_overview.txt', 'r', encoding='utf-8') as task:
        print('\nTASK OVERVIEW STATS:\n')
        for line in task:
            print(line.strip())
        
    with open('user_overview.txt', 'r', encoding='utf-8') as task:
        print('\nUSER OVERVIEW STATS:\n')
        for line in task:
            print(line.strip())
            
    exit_menu()

# Generate the task overview text file.
def generate_task_overview():
    task_dictionary = task_dict()
    completed_tasks = 0
    uncompleted_tasks = 0
    overdue_tasks = 0
    
    # Open the file, or creates it if it doesn't exist.
    # Reads each task from the task_dict function.
    # And applies the logic to write to the file.
    with open('task_overview.txt', 'w', encoding='utf-8') as task_overview:
        for count in task_dictionary:
            task = task_dictionary[count]
            if 'Yes' == task['task_complete']:
                completed_tasks += 1
            elif 'No' == task['task_complete']:
                uncompleted_tasks += 1
            
            # Comparing the dates to check if the task is overdue.
            datetime_object = datetime.datetime.strptime(task['date_due'], '%d %b %Y') # 'strptime()' parses a string representing a time according to a format.
            if datetime_object < datetime.datetime.today() and 'No' == task['task_complete']: # 'today()' method of date class under datetime module returns a date object which contains the value of Today's date.
                overdue_tasks += 1
                
        percentage_incomplete = (uncompleted_tasks * 100)/(len(task_dictionary))
        percentage_overdue = (overdue_tasks * 100)/(len(task_dictionary))

        # Print / write everything to the file.
        task_overview.write(f"Total number of tasks generated using Task Manager: {len(task_dictionary)}\n")
        task_overview.write(f"Number of completed tasks: {completed_tasks}\n")
        task_overview.write(f"Number of uncompleted tasks: {uncompleted_tasks}\n")
        task_overview.write(f"Number of uncompleted tasks that are overdue: {overdue_tasks:.0f}\n")
        task_overview.write(f"Percentage of uncompleted tasks: {percentage_incomplete:.0f}%\n")
        task_overview.write(f"Percentage of uncompleted overdue tasks: {percentage_overdue:.0f}%\n")
    
        print("Task_overview.txt written.")