保存数据到csv
csv 逗号分隔值
一、写入
1、列表
单行添加
import csv # with open(file='a.csv', mode='w', encoding='utf-8', newline='') as f: write = csv.writer(f) write.writerow(['id', 'name', 'age']) write.writerow(['1001', 'tom', 23]) write.writerow(['1002', 'alex', 34]) write.writerow(['1003', 'Bob', 16]) # newline='' 作用去除行,若没有每添加一条数据,添加一空行
批量添加
import csv # header = ['id', 'name', 'age'] body = [ ['1001', 'tom', 23], ['1002', 'alex', 34], ['1003', 'Bob', 16] ] with open(file='b.csv', mode='w', encoding='utf-8', newline='') as f: write = csv.writer(f) write.writerow(header) write.writerows(body) # 注意:批量添加用writerows()
2、字典
单行添加
import csv # header = ['id', 'name', 'age'] with open(file='c.csv', mode='w', encoding='utf-8', newline='') as f: write = csv.DictWriter(f, fieldnames=header) write.writeheader() write.writerow({'id': '1001', 'name': 'tom', 'age': 23}) write.writerow({'id': '1002', 'name': 'alex', 'age': 34}) write.writerow({'id': '1003', 'name': 'Bob', 'age': 45})
批量添加
import csv # header = ['id', 'name', 'age'] body_dic = [ {'id': '1001', 'name': 'tom', 'age': 23}, {'id': '1002', 'name': 'alex', 'age': 34}, {'id': '1003', 'name': 'Bob', 'age': 45} ] with open(file='d.csv', mode='w', encoding='utf-8', newline='') as f: write = csv.DictWriter(f, fieldnames=header) write.writeheader() write.writerows(body_dic)
二、读取
1、列表
import csv # with open(file='d.csv', mode='r', encoding='utf-8', newline='') as f: reader = csv.reader(f) for row in reader: print(row)
2、字典
import csv # with open(file='d.csv', mode='r', encoding='utf-8', newline='') as f: reader = csv.DictReader(f) for row in reader: print(dict(row))