Python 讀寫 csv 檔案

在 python 中有內建 csv 模組,可以直接用來讀寫 csv 檔案。

我們先建立一個範例的 csv 檔案:
    
id,name
1,小明
2,大頭
    

    
import csv

with open('data.csv', mode='r', encoding='utf-8') as file:
    reader = csv.reader(file)  # 讀取 CSV 檔案
    header = next(reader)  # 讀取標題資料

    print("標題:", header) # 標題: ['id', 'name']

    for row in reader:
        print(row)
        # ['1', '小明']
        # ['2', '大頭']
    



文章撰寫中...請稍後...

參考資料:
python docs - csv — CSV File Reading and Writing

留言