Python与CSV文件的操作

计算每个人的总分

csv源文件如下,计算客观分和主观分的总和,并添加在后面

分数处理前

处理完之后,应该有如下效果

分数处理后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
scores=[]
fr=open("成绩分析.csv","r") ##打开文件,若该文件不与py文件处于同一位置,则需要加路径

for line in fr:
line=line.replace("\n","") ##去掉换行符
person=line.split(",") ##变成列表
scores.append(person) ##变成二维数组
fr.close()
isFirst=True
for person in scores:
if isFirst:
person.append("sum") ##在第一行添加一个"sum"
isFirst=False
else:
s=0
for mark in person[3:]: ##读取成绩
s+=float(mark)
person.append("{:.2f}".format(s)) ##添加成绩
print(scores)
fw=open("result.csv","w")
for person in scores:
for e in person:
print(e,",",sep="",end="",file=fw) ##写入每行的数据
print(file=fw) ##换行
fw.close()

求总分,主观分和客观分的最高最低值,还有它们的均值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
scores=[]
fr=open("result.csv","r")
for line in fr:
line=line.replace("\n","")
person=line.split(",")
scores.append(person)
fr.close

##初始化
sMax,sMin=-99,999
sjMax,sjMin=-99,999
ojMax,ojMin=-99,999
sAvg,sjAvg,ojAvg=0,0,0
sSum,sjSum,ojSum=0,0,0

##找出最大最小值
count=0
isFirst=True
for person in scores:
if isFirst:
isFirst=False
else:
mark=float(person[5])
sSum+=mark
if mark>=sMax:
sMax=mark
if mark<=sMin:
sMin=mark

mark=float(person[4])
sjSum+=mark
if mark>=sjMax:
sjMax=mark
if mark<=sjMin:
sjMin=mark

mark=float(person[3])
ojSum+=mark
if mark>=ojMax:
ojMax=mark
if mark<=ojMin:
ojMin=mark

SUM=[]
sMax1=[]
sMin1=[]
sjMax1=[]
sjMin1=[]
ojMax1=[]
ojMin1=[]

##将符合条件的人员添加到对应的列表中
isFirst=True
for person in scores:
if isFirst:
isFirst=False
else:
count+=1
print(person)
mark=float(person[5])
if mark==sMax:
sMax1.append(person)

if mark==sMin:
sMin1.append(person)

mark=float(person[4])
if mark==sjMax:
sjMax1.append(person)

if mark==sjMin:
sjMin1.append(person)

mark=float(person[3])
if mark==ojMax:
ojMax1.append(person)

if mark==ojMin:
ojMin1.append(person)

##计算均值
sAvg=sSum/count
sjAvg=sjSum/count
ojAvg=ojSum/count

##将结果写入一个新的csv文件
fw=open("汇总.csv","w")
for i in sMax1:
print("总分最高",",",i[0],",",i[1],",",i[5],file=fw)
for i in sMin1:
print("总分最低",",",i[0],",",i[1],",",i[5],file=fw)
for i in sjMax1:
print("主观分最高",",",i[0],",",i[1],",",i[4],file=fw)
for i in sjMin1:
print("主观分最低",",",i[0],",",i[1],",",i[4],file=fw)
for i in ojMax1:
print("客观分最高",",",i[0],",",i[1],",",i[3],file=fw)
for i in ojMin1:
print("客观分最低",",",i[0],",",i[1],",",i[3],file=fw)
print("总分分均值",",","{:.2f}".format(sAvg),file=fw)
print("主观分均值",",","{:.2f}".format(sjAvg),file=fw)
print("客观分均值",",","{:.2f}".format(ojAvg),file=fw)
fw.close()