python存储csv文件

源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import csv
headers = ["username","age","height"]
values = [("张三","18","180"),("李四","19","190"),("王五","18","160")]
def csv_1():
headers = ["username", "age", "height"]
values = [("张三", "18", "180"), ("李四", "19", "190"), ("王五", "18", "160")]
with open("classroom1.csv","w",encoding="utf-8",newline="") as fp:
new_fp = csv.writer(fp)
new_fp.writerow(headers)
new_fp.writerows(values)

def csv_2():
headers = ["username", "age", "height"]
values = [{"username":"张三","age":"18","height":"180"},{"username":"李四","age":"19","height":"190"},{"username":"王五","age":"18","height":"160"}]
with open("classroom2.csv","w",encoding="utf-8",newline="") as fp:
writer = csv.DictWriter(fp,headers)
writer.writeheader()
writer.writerows(values)
if __name__ == '__main__':
# csv_1()
csv_2()

csv2长这样:

1
2
3
4
username,age,height
张三,18,180
李四,19,190
王五,18,160