寫入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()
相關文章
相關標籤/搜索