直接上代码
import csv
def read_csv_demo1():
with open('stock.csv', 'r') as f:
# reader是一个迭代器
reader = csv.reader(f)
next(reader) # 选出第一行
for i in reader:
name = i[3]
volumn = i[-1]
print({'name': name, 'volumn': volumn})
def read_csv_demo2():
with open('stock.csv', 'r') as f:
# 使用DictReader创建的reader对象
# 不会包含标题那行的数据
# reader 是一个迭代器,遍历这个迭代器,返回来的是一个字典
reader = csv.DictReader(f)
for i in reader:
value = {'name': i['secShortName'], 'voluma': i['turnoverVol']}
print(value)
def write_csv_demo1():
headers = ['username', 'age', 'height']
values = [
('张三', 18, 181),
('李四', 19, 190),
('王五', 20, 170)
]
with open('classroom.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers) # 一行一行的写
writer.writerows(values) # 多行写入
def write_csv_demo2():
headers = ['username', 'age', 'height']
values = [
{'username': '张三', 'age': 18, 'height': 180},
{'username': '李四', 'age': 19, 'height': 190},
{'username': '王五', 'age': 17, 'height': 170},
]
with open('classroom1.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, headers) # 以字典形式写入,并传入表头
# 写入表头数据的时候,需要调用writeheader方法
writer.writeheader()
writer.writerows(values)
if __name__ == '__main__':
read_csv_demo1()
read_csv_demo2()
write_csv_demo1()
write_csv_demo2()