用 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