Here's a Python application that creates a simple command-line to-do list with basic functionality (add, view, mark as complete, and delete tasks). I'll use a text file to store the tasks persistently.
import json
import os
from datetime import datetime
class TodoList:
def __init__(self, filename="todo_list.json"):
self.filename = filename
self.tasks = self.load_tasks()
def load_tasks(self):
"""Load tasks from the JSON file"""
if os.path.exists(self.filename):
with open(self.filename, 'r') as file:
return json.load(file)
return []
def save_tasks(self):
"""Save tasks to the JSON file"""
with open(self.filename, 'w') as file:
json.dump(self.tasks, file, indent=4)
def add_task(self, description):
"""Add a new task to the list"""
task = {
'id': len(self.tasks) + 1,
'description': description,
'completed': False,
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
self.tasks.append(task)
self.save_tasks()
print(f"\nTask added successfully! (ID: {task['id']})")
def view_tasks(self):
"""Display all tasks"""
if not self.tasks:
print("\nNo tasks found!")
return
print("\n=== To-Do List ===")
for task in self.tasks:
status = "✓" if task['completed'] else "✗"
print(f"[{status}] ID: {task['id']} - {task['description']}")
print(f" Created: {task['created_at']}")
print("==================")
def mark_complete(self, task_id):
"""Mark a task as complete"""
for task in self.tasks:
if task['id'] == task_id:
task['completed'] = True
self.save_tasks()
print(f"\nTask {task_id} marked as complete!")
return
print(f"\nTask with ID {task_id} not found!")
def delete_task(self, task_id):
"""Delete a task"""
for i, task in enumerate(self.tasks):
if task['id'] == task_id:
deleted_task = self.tasks.pop(i)
# Reassign IDs to maintain sequential order
for j, t in enumerate(self.tasks):
t['id'] = j + 1
self.save_tasks()
print(f"\nTask '{deleted_task['description']}' deleted!")
return
print(f"\nTask with ID {task_id} not found!")
def main():
todo_list = TodoList()
while True:
print("\n=== To-Do List Application ===")
print("1. Add Task")
print("2. View Tasks")
print("3. Mark Task as Complete")
print("4. Delete Task")
print("5. Exit")
choice = input("\nEnter your choice (1-5): ")
if choice == '1':
description = input("Enter task description: ")
todo_list.add_task(description)
elif choice == '2':
todo_list.view_tasks()
elif choice == '3':
try:
task_id = int(input("Enter task ID to mark as complete: "))
todo_list.mark_complete(task_id)
except ValueError:
print("\nPlease enter a valid number!")
elif choice == '4':
try:
task_id = int(input("Enter task ID to delete: "))
todo_list.delete_task(task_id)
except ValueError:
print("\nPlease enter a valid number!")
elif choice == '5':
print("\nGoodbye!")
break
else:
print("\nInvalid choice! Please try again.")
if __name__ == "__main__":
main()
Features of the To-Do List App:
- Persistent Storage: Tasks are saved to a JSON file (
todo_list.json) so they persist between sessions.
- Task Management:
- Add new tasks with a description and timestamp.
- View all tasks with their status (completed or not).
- Mark tasks as complete.
- Delete tasks.
- User-Friendly Interface: A simple command-line menu to interact with the app.
- Error Handling: Basic error handling for invalid inputs (e.g., non-numeric task IDs).
How to Use the App:
- Run the Script: Save the code in a file (e.g.,
todo_list.py) and run it using Python:
python todo_list.py
- Menu Options:
- Choose
1 to add a new task.
- Choose
2 to view all tasks.
- Choose
3 to mark a task as complete (you'll need the task ID).
- Choose
4 to delete a task (you'll need the task ID).
- Choose
5 to exit the app.
Example Output:
=== To-Do List Application ===
1. Add Task
2. View Tasks
3. Mark Task as Complete
4. Delete Task
5. Exit
Enter your choice (1-5): 1
Enter task description: Buy groceries
Task added successfully! (ID: 1)
=== To-Do List Application ===
1. Add Task
2. View Tasks
3. Mark Task as Complete
4. Delete Task
5. Exit
Enter your choice (1-5): 2
=== To-Do List ===
[✗] ID: 1 - Buy groceries
Created: 2023-10-05 14:30:22
==================
Notes:
- Dependencies: This app uses only Python's standard library (
json, os, datetime), so no external packages are required.
- File Storage: Tasks are stored in a file named
todo_list.json in the same directory as the script. If the file doesn't exist, it will be created automatically.
- Improvements: You could enhance this app by:
- Adding a graphical user interface (GUI) using libraries like
tkinter or PyQt.
- Adding categories or priorities to tasks.
- Implementing due dates and reminders.
- Adding the ability to edit tasks.
Let me know if you'd like to add any of these enhancements or need further clarification!