I made a simple program that stores tasks in the file and allows user to manage them. I’m interested if my implementation is efficient and could I do something better. I’m not sure whether loading all data from file to memory and again saving it in file is a good way to implement list saving tasks.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os CHOICE_LIST_TASKS = 1 CHOICE_ADD_TASK = 2 CHOICE_REMOVE_TASK = 3 CHOICE_QUIT = 4 def read_int(prompt='> ', errmsg='Invalid number!'): num = None while num is None: try: num = int(input(prompt)) except ValueError: print(errmsg) return num def display_menu(): print('What do you want to do?') print('(1) List all tasks') print('(2) Add a new task') print('(3) Delete task') print('(4) Quit') choice = None file = None if not os.path.exists('tasks'): file = open('tasks', 'w+') else: file = open('tasks', 'r+') tasks = () for line in file.readlines(): tasks.append(line.strip()) while choice != CHOICE_QUIT: display_menu() choice = read_int() if choice == CHOICE_LIST_TASKS: if len(tasks) == 0: print('Task list is empty!') else: print('Tasks:') for x in tasks: print(x) elif choice == CHOICE_ADD_TASK: desc = input('Which task do you want to do? ') index = tasks.append(desc) print('Successfully added a new task!') elif choice == CHOICE_REMOVE_TASK: if len(tasks) == 0: print('Task list is empty!') else: for x in tasks: print(tasks.index(x), x) index = read_int('Which task do you want to delete? ') try: tasks.pop(index) print('Successfully deleted task!') except IndexError: print('Please enter proper task number') elif choice == CHOICE_QUIT: print('Good bye!') else: print('Invalid choice!') file = open('tasks', 'w+') for x in tasks: file.write(x + 'n')