存取CSV
Python 內建 csv
模組,可以輕鬆處理 CSV(逗號分隔值)檔案。
✅ 讀取 CSV
import csv
with open("data.csv", newline="", encoding="utf-8") as file:
reader = csv.reader(file) # 建立 CSV 讀取器
for row in reader:
print(row) # 逐行讀取並輸出
✅ 寫入 CSV
import csv
data = [["姓名", "年齡"], ["小明", 25], ["小華", 30]]
with open("output.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file) # 建立 CSV 寫入器
writer.writerows(data) # 寫入多行
📝 總結
- 讀取 CSV →
csv.reader(file)
- 寫入 CSV →
csv.writer(file).writerows(data)
🚀 簡單易用,適用於處理表格數據! 😊