【再回首Python之美】【文件】根据成绩表,生成每个学生总成绩表

有学生成绩表:

    一个学生一行,如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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值