Skip to main content

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

· 2 min read

🧠 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