用 Python 讀寫
CSV(逗號分隔值)是一種用於儲存表格資料的簡單檔案格式,例如電子表格。這是如何在 Python 中編寫和讀取資料的最小示例。
將資料寫入 CSV 檔案:
import csv
data = [["Ravi", "9", "550"], ["Joe", "8", "500"], ["Brian", "9", "520"]]
with open('students.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerows(data)
從 CSV 檔案中讀取資料:
import csv
with open('students.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',',)
for row in spamreader:
print("Name: {} class: {} Marks: {}".format(row[0], row[1], row[2]))
output:
Name: Ravi class: 9 Marks: 550
Name: Joe class: 8 Marks: 500
Name: Brian class: 9 Marks: 520