Skip to Content

Ngày 31 - Python hằng ngày 365 ngày - Quản lý công việc với CSV

🐍 Ngày 31 - Python hằng ngày 365 ngày - Quản lý công việc với CSV

🧠 Mục tiêu

Học cách đọc, ghi và cập nhật file CSV để lưu danh sách công việc (To-do List).

📂 File CSV mẫu

Task,Status
Chao co,Pending

🧪 Code Python hoàn chỉnh

import csv

FILENAME = "tasks.csv"

# Đọc dữ liệu từ file CSV
def read_tasks():
    tasks = []
    try:
        with open(FILENAME, mode='r', newline='', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            for row in reader:
                tasks.append(row)
    except FileNotFoundError:
        print("⚠️ File chưa tồn tại. Tạo mới khi ghi.")
    return tasks

# Ghi dữ liệu trở lại file CSV
def write_tasks(tasks):
    with open(FILENAME, mode='w', newline='', encoding='utf-8') as file:
        fieldnames = ['Task', 'Status']
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(tasks)

# Hiển thị danh sách công việc
def view_tasks(tasks):
    print("\n📋 DANH SÁCH CÔNG VIỆC:")
    for idx, task in enumerate(tasks, 1):
        print(f"{idx}. {task['Task']} - {task['Status']}")

# Thêm công việc mới
def add_task(tasks):
    task_name = input("📝 Nhập tên công việc: ")
    tasks.append({"Task": task_name, "Status": "Pending"})
    write_tasks(tasks)
    print("✅ Đã thêm thành công!")

# Menu
def main():
    while True:
        print("\n===== MENU TO-DO LIST =====")
        print("1. Xem danh sách")
        print("2. Thêm công việc")
        print("3. Thoát")
        choice = input("👉 Nhập lựa chọn: ")

        tasks = read_tasks()

        if choice == '1':
            view_tasks(tasks)
        elif choice == '2':
            add_task(tasks)
        elif choice == '3':
            print("👋 Tạm biệt!")
            break
        else:
            print("⚠️ Lựa chọn không hợp lệ.")

if __name__ == "__main__":
    main()


💾 Kết quả đầu ra

Giả sử bạn đã thêm 2 task mới:

Task,Status
Chao co,Pending
Hoc lap trinh,Pending
Di choi,Pending

/* Tối ưu font, khoảng cách và màu chủ đạo */ body { font-family: 'Inter', sans-serif; color: #2e3a59; } h1, h2, h3 { color: #2a7a4d; /* màu xanh giống Docusaurus */ font-weight: 700; } a { color: #2a7a4d; text-decoration: none; } a:hover { text-decoration: underline; } /* Bo tròn và đổ bóng cho khối nội dung */ .card, .oe_structure { border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); padding: 1.5rem; }