有学生成绩表:
一个学生一行,如Tom 98 89 76 68
总成绩表:
一个学生一行,如Tom :331
代码如下:
#score.py
score_file = "C:\Python27\mydata\score.txt"
sum_file = "C:\Python27\mydata\sum.txt"
def lineCount(file_path):
f = file(filepath)
lines = f.readlines()
f.close()
return len(lines)
def writeFile(file_path, data_list):
fout = file(sum_file, 'w')
fout.writelines(data_list)
fout.close()
def dumpFile(file_path):
fin = file(file_path)
lines = fin.readlines()
print lines
fin.close()
def sumList(score_file):
f = file(score_file)
lines = f.readlines()
f.close()
sum_list = [] #save every student score sum
for line in lines: #John 86 98 79 66
score_list = line.split()
total = 0 #save current student score sum
student = score_list[0] #save current student name
for score in score_list[1:]:
total += int(score)
result = '%s\t:%d\n' % (student, total)
sum_list.append(result) #append result to list tail
print sum_list
writeFile(sum_file, sum_list)
return sum_list
#test
dumpFile(score_file)
sumList(score_file)
dumpFile(sum_file)
#学生成绩表score_file
#Tom 1 1 1 1
#Joan 2 2 2 2
#Niki 3 3 3 3
#Betty 4 4 4 4
#Linda 5 5 5 5
#Lily 6 6 6 6
#Thomas 7 7 7 7
#Jack 8 8 8 8
#Kevin 9 9 9 9
#Lisa 10 10 10 10
#Ann 11 11 11 11
#Diana 12 12 12 12
#学生总成绩表sum_file
#Tom :4
#Joan :8
#Niki :12
#Betty :16
#Linda :20
#Lily :24
#Thomas :28
#Jack :32
#Kevin :36
#Lisa :40
#Ann :44
#Diana :48
(end)