写入csv文件的两种方式
1 #encoding: utf-8
2
3 import csv
4
5 def write_csv():
6 headers = ['username', 'age', 'height']
7 # values内部是以元组的形式存在
8 values = [
9 ('張三', 18, 180),
10 ('李四', 19, 190),
11 ('王五', 20, 160)
12 ]
13
14 with open('classroom.csv', 'w', encoding='utf-8', newline='') as fp:
15 writer = csv.writer(fp)
16 writer.writerow(headers)
17 writer.writerows(values)
18
19
20
21 if __name__ == '__main__':
22 write_csv()
#encoding: utf-8
import csv
def write_csv_demo2():
headers = ['username', 'age', 'height']
#values内部是以字典的形式存在
values = [
{'username':'张三','age':18,'height':180},
{'username':'李四','age':19,'height':190},
{'username':'王五','age':20,'height':160}
]
with open('classroo1.csv','w',encoding='utf-8',newline='') as fp:
writer = csv.DictWriter(fp,headers)
# 写入表头数据的时候,需要调用writeheader方法
writer.writeheader()
writer.writerows(values)
if __name__ == '__main__':
write_csv()