Okay, let's create a simple command-line To-Do List app in Python that saves and loads tasks from a JSON file.
Features:
Add new tasks.
View all tasks (showing status: completed or not).
Mark a task as completed.
Remove a task.
Save tasks to a file.
Load tasks from a file when the app starts.
Quit the application.
Requirements:
Python 3 installed.
No external libraries needed besides the built-in json and os modules.
Code:
python
import json
import os
# Define the file where tasks will be stored
TODO_FILE = 'todo_list.json'
def load_tasks():
"""Loads tasks from the JSON file."""
if os.path.exists(TODO_FILE):
try:
with open(TODO_FILE, 'r') as f:
# Handle empty file case
content = f.read()
if not content:
return []
tasks = json.loads(content)
# Ensure tasks is a list (in case file content is malformed)
if isinstance(tasks, list):
return tasks
else:
print(f"Warning: Data in {TODO_FILE} is not a list. Starting fresh.")
return []
except json.JSONDecodeError:
print(f"Error decoding JSON from {TODO_FILE}. File might be corrupt. Starting fresh.")
return []
except Exception as e:
print(f"An unexpected error occurred loading tasks: {e}. Starting fresh.")
return []
else:
return [] # Return an empty list if the file doesn't exist
def save_tasks(tasks):
"""Saves the current list of tasks to the JSON file."""
try:
with open(TODO_FILE, 'w') as f:
json.dump(tasks, f, indent=4) # indent=4 for readability
except Exception as e:
print(f"Error saving tasks: {e}")
def display_menu():
"""Displays the main menu options."""
print("\n--- To-Do List Menu ---")
print("1. View Tasks")
print("2. Add Task")
print("3. Mark Task as Complete")
print("4. Remove Task")
print("5. Save Tasks")
print("6. Quit")
print("-----------------------")
def view_tasks(tasks):
"""Displays all tasks with their status."""
if not tasks:
print("\nNo tasks in the list yet!")
return
print("\n--- Your Tasks ---")
for index, task in enumerate(tasks):
status = "Done" if task['completed'] else "Pending"
print(f"{index + 1}. [{status}] {task['task']}")
print("--------------------")
def add_task(tasks):
"""Prompts user for a new task and adds it to the list."""
description = input("Enter the new task description: ").strip()
if description:
tasks.append({"task": description, "completed": False})
print("Task added.")
else:
print("Task description cannot be empty.")
def get_task_index(tasks):
"""Helper function to get a valid task index from user input."""
if not tasks:
print("No tasks to select.")
return None
while True:
try:
index_str = input("Enter the task number: ")
task_index = int(index_str) - 1 # Adjust to 0-based index
if 0 <= task_index < len(tasks):
return task_index
else:
print("Invalid task number. Please enter a number from the list.")
except ValueError:
print("Invalid input. Please enter a number.")
def mark_complete(tasks):
"""Marks a selected task as completed."""
view_tasks(tasks) # Show tasks with numbers
if not tasks:
return
print("\nEnter the number of the task to mark as complete.")
task_index = get_task_index(tasks)
if task_index is not None:
tasks[task_index]['completed'] = True
print(f"Task '{tasks[task_index]['task']}' marked as complete.")
def remove_task(tasks):
"""Removes a selected task from the list."""
view_tasks(tasks) # Show tasks with numbers
if not tasks:
return
print("\nEnter the number of the task to remove.")
task_index = get_task_index(tasks)
if task_index is not None:
removed_task = tasks.pop(task_index)
print(f"Task '{removed_task['task']}' removed.")
def main():
"""Main function to run the To-Do List application."""
tasks = load_tasks()
print("To-Do List application loaded.")
while True:
display_menu()
choice = input("Enter your choice: ").strip()
if choice == '1':
view_tasks(tasks)
elif choice == '2':
add_task(tasks)
elif choice == '3':
mark_complete(tasks)
elif choice == '4':
remove_task(tasks)
elif choice == '5':
save_tasks(tasks)
print("Tasks saved.")
elif choice == '6':
print("Saving tasks before quitting...")
save_tasks(tasks)
print("Goodbye!")
break # Exit the loop
else:
print("Invalid choice. Please try again.")
# Optional: Automatically save after certain actions (like add, complete, remove)
# This makes it less likely to lose data if the user forgets to save
# Uncomment the next line if you want auto-save
# save_tasks(tasks) # Auto-save after each modification
# Run the main function when the script is executed
if __name__ == "__main__":
main()
How to Use:
Save the code above as a Python file (e.g., todo_app.py).
Open your terminal or command prompt.
Navigate to the directory where you saved the file.
Run the script using: python todo_app.py
Follow the on-screen menu to interact with your to-do list.
Tasks will be saved to a file named todo_list.json in the same directory when you choose option 5 or when you quit (option 6).
This provides a solid foundation for a command-line to-do list application. You can expand upon it by adding features like priorities, due dates, editing tasks, filtering tasks, etc.