Skip to main content

🐍 Ngày 30 - Python hằng ngày 365 ngày - Làm việc với File CSV trong Python

· 2 min read

📘 Python To-Do List App với CSV

📝 Mục tiêu

  • Quản lý danh sách công việc sử dụng Python và lưu trữ bằng file .csv
  • Cho phép người dùng xem, thêm và lưu công việc

📁 File CSV đầu vào (tasks.csv)

Task,Status
Post Fanpage,Done
Post Group,Pending

🔧 Mã nguồn Python đầy đủ

import csv
import os

CSV_FILE = "todo_tasks.csv"

def load_tasks():
tasks = []
if os.path.exists(CSV_FILE):
with open(CSV_FILE, newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
status = row["Status"].strip().lower()
tasks.append({
"Task": row["Task"],
"completed": status in ["done", "completed", "true"]
})
return tasks

def save_tasks(tasks):
with open(CSV_FILE, "w", newline='', encoding='utf-8') as csvfile:
fieldnames = ["Task", "Status"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for task in tasks:
status = "Done" if task["completed"] else "Pending"
writer.writerow({"Task": task["Task"], "Status": status})

def show_tasks(tasks):
print("\n📋 Danh sách công việc:")
for idx, task in enumerate(tasks, 1):
status = "✅" if task["completed"] else "⏳"
print(f"{idx}. {task['Task']} {status}")

def add_task(tasks):
new_task = input("🔹 Nhập tên công việc mới: ")
tasks.append({"Task": new_task, "completed": False})
print("✅ Đã thêm công việc mới.")

def main():
tasks = load_tasks()

while True:
print("\n----- MENU -----")
print("1. Xem danh sách công việc")
print("2. Thêm công việc mới")
print("3. Thoát")
choice = input("Chọn một tùy chọn: ")

if choice == "1":
show_tasks(tasks)
elif choice == "2":
add_task(tasks)
save_tasks(tasks)
elif choice == "3":
print("👋 Tạm biệt!")
break
else:
print("❌ Lựa chọn không hợp lệ. Vui lòng thử lại.")

if __name__ == "__main__":
main()

💡 Mở rộng đề xuất

  • Đánh dấu hoàn thành công việc
  • Xóa công việc
  • Sắp xếp danh sách theo trạng thái hoặc thời gian tạo