10 Mini Project และแนวทางต่อยอด
Mini Project และแนวทางต่อยอด
บทนี้จะรวมสิ่งที่เรียนมาเป็นโปรเจกต์เล็ก: อ่านไฟล์ยอดขาย CSV แล้วสร้าง summary เป็น JSON
เป้าหมาย
โปรแกรมควรทำงานได้ดังนี้
- อ่านไฟล์
orders.csv - รวมยอดขายทั้งหมด
- นับจำนวน order
- หา order ที่มียอดสูงสุด
- เขียนผลลัพธ์ลง
summary.json
ตัวอย่าง input
order_id,customer,amount
1,Ann,1200
2,Bob,850
3,Cat,2400
โค้ดตัวอย่าง
import csv
import json
from datetime import datetime
def read_orders(file_path):
orders = []
with open(file_path, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
orders.append({
"order_id": row["order_id"],
"customer": row["customer"],
"amount": float(row["amount"]),
})
return orders
def summarize_orders(orders):
total_amount = 0
max_order = None
for order in orders:
total_amount += order["amount"]
if max_order is None or order["amount"] > max_order["amount"]:
max_order = order
return {
"order_count": len(orders),
"total_amount": total_amount,
"max_order": max_order,
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
def write_json(file_path, data):
with open(file_path, "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=2)
try:
orders = read_orders("orders.csv")
summary = summarize_orders(orders)
write_json("summary.json", summary)
print("สร้าง summary.json สำเร็จ")
except FileNotFoundError:
print("ไม่พบไฟล์ orders.csv")
except ValueError:
print("amount ต้องเป็นตัวเลข")
สิ่งที่ใช้จากบทก่อนหน้า
- ตัวแปรและชนิดข้อมูล
- list และ dictionary
- function
- file handling
- CSV และ JSON
- error handling
- datetime
แนวทางต่อยอด
หลังจบพื้นฐานนี้ สามารถต่อยอดได้หลายทาง
pandasสำหรับวิเคราะห์ข้อมูลrequestsสำหรับเรียก APIFastAPIสำหรับสร้าง backendpytestสำหรับเขียน test- SQL สำหรับดึงข้อมูลจาก database
- Airflow หรือ cron สำหรับตั้งเวลารันงาน
แบบฝึกหัดต่อยอด
- เพิ่มค่า
average_amount - สรุปยอดขายแยกตาม customer
- แยก function ไปไว้ในไฟล์
order_utils.py - รับชื่อไฟล์ input จาก
input() - ถ้าไม่มี order ให้โปรแกรมไม่ error