码迷,mamicode.com
首页 > 其他好文 > 详细

4_4 写入csv文件

时间:2020-06-15 23:09:20      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:__name__   encoding   value   方法   code   main   写入   div   port   

 

 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()

 

4_4 写入csv文件

标签:__name__   encoding   value   方法   code   main   写入   div   port   

原文地址:https://www.cnblogs.com/sruzzg/p/13138254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!