# 实训7-1
import csv
file_path = r'D:\work\Python编程基础\Python编程基础\第7章 文件基础\实训数据\iris.csv'
# 读取数据
with open(file_path, 'r') as f:
my_reader = csv.DictReader(f)
iris = [iris_item for iris_item in my_reader]
print(iris)
# 提取字典的键
my_key = []
for i in iris[0].keys():
my_key.append(i)
my_keys = my_key[1:5] # 需要求平均的键的集合
print(my_keys)
# 计算各属性列的平均值
my_work = {}
for i in my_keys:
temp = [float(iris_item[i]) for iris_item in iris] # 将数据读为列表
print(temp)
my_work[i] = [sum(temp)/len(temp)]
# 输出各属性列的平均值
print(my_work)
#写入文件
fileName=r"d:\a.csv"
with open(fileName,"w",newline="") as f:
writer=csv.DictWriter(f,keyIris)
writer.writeheader()
writer.writerows(iris)