python 将数据写入到 .csv 文件里
import json
import os
import csv
class SaveCSV(object):
def save(self, keyword_list, path, item):
try:
# 第一次打开文件时,第一行写入表头
if not os.path.exists(path):
with open(path, "w", newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=keyword_list) # 写字典的方法
writer.writeheader() # 写表头的方法
# 追加写入内容
with open(path, "a", newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=keyword_list)
writer.writerow(item) # 按行写入数据
print("写入成功")
# 报错将吧错误记录到error.txt文件里
except Exception as e:
print("写入失败 = ", e)
# 记录错误数据
with open("error.txt", "w") as f:
f.write(json.dumps(item) + ",\n")
pass
if __name__ == '__main__':
# 保存的文件名路径
path = "/Users/mac/test1.csv"
# 案例字典数据
item = {'千千': 666, '问问': 555, '蛋蛋': 999}
# 保存的表头
item_list = ["千千", "问问", "蛋蛋"]
s = SaveCSV()
"""
循环3次 插入3行数据
"""
for i in range(3):
s.save(item_list, path, item)
效果类似如下:
千千 | 问问 | 蛋蛋 |
---|---|---|
666 | 555 | 999 |
666 | 555 | 999 |
666 | 555 | 999 |