1 """写入csv文件""" 2 3 4 import csv 5 6 # 方法一: 7 def write_csv_demo1(): 8 headers = ['username', 'age', 'height'] 9 values = [ 10 ('张三', 18, 180), 11 ('李四', 19, 190), 12 ('王五', 20, 120) 13 ] 14 with open('csvwriter1.csv', 'w', encoding='gbk', newline='') as fp: 15 fp.writer = csv.writer(fp) 16 fp.writer.writerow(headers) 17 fp.writer.writerows(values) 18 19 # 方法二: 20 def write_csv_demo2(): 21 headers = ['username', 'age', 'height'] 22 values = [ 23 {'username': '张三', 'age': 18, 'height': 180}, 24 {'username': '李四', 'age': 19, 'height': 190}, 25 {'username': '王五', 'age': 20, 'height': 120} 26 ] 27 with open('csvwriter2.csv', 'w', encoding='utf-8', newline='') as fp: 28 write = csv.DictWriter(fp, headers) 29 write.writeheader() # 写入表头信息 30 write.writerows(values) 31 32 if __name__ == "__main__": 33 write_csv_demo1() 34 write_csv_demo2()