# -*- coding: utf-8 -*-
import csv
# 写入列表
headers = ["index", "a_name", "b_name"]
values = [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]
# 1. values 可迭代,list,tuple
# 2. 若结果中出现间隔空行,就加newline='' or 'w'-->'wb+'
with open('listdemo.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(values)
# 写入字典
headers = ['class', 'name', 'sex', 'height', 'year']
values = [{'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
{'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22}]
# 若结果中出现间隔空行,就加newline='' or 'w'-->'wb+'
with open('dictdemo.csv', 'w', newline='') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(values)
# 读取
# 按照列表形式取值
# 使用csv库的内置方法reader, 相当于xlrd读取excel,当然更方便了
with open("listdemo.csv", "r") as f:
reader = csv.reader(f) # reder是一个迭代器
next(reader) # 跳过表头/可选择不跳过
for line in reader:
print(line)
# 按照字典形式取值
with open("dictdemo.csv", "r") as f:
reader = csv.DictReader(f)
for line in reader:
print(line, ' --- ', type(line))
print({'name':line['name'], 'sex': line['sex']})