读取文件内容、计算学生成绩总分、再写入文件(python I/O流)

您所在的位置:网站首页 用公式计算总成绩和成绩排名 读取文件内容、计算学生成绩总分、再写入文件(python I/O流)

读取文件内容、计算学生成绩总分、再写入文件(python I/O流)

2024-07-10 20:04| 来源: 网络整理| 查看: 265

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

目录

一、题目:

二、文件位置(路径)及内容:

三、 代码:

1、读取文件

2、计算总分

3、写入文件

4、全部代码:

5、效果截图

四、总结

一、题目:

      现有score.txt文件中有学生的学号、姓名、语文成绩、数学成绩、英语成绩,要求计算每一位学生的总成绩并排序(降序),最后写入score1.txt文件中。

二、文件位置(路径)及内容:

1.路径

提示:可以自己定义文件的路径,新建一个文本即可

2.score.txt文件的内容:(要提前写好,用来访问的)

 

三、 代码: 1、读取文件 with open("E:\存/score.txt", "r", encoding="Utf-8") as f1: txts = f1.readlines() # print(txts)读取文件 2、计算总分 score = [] # 添加成绩列 for i in txts: ls = i.split() score.append((i.split())) # print(score) score[0].append("总分") # 第一行的最后一个加上总分 for h in score[1:]: # 将每一行的成绩加到,每一行的总分 zf = float(h[2]) + float(h[3]) + float(h[4]) h.append(str(zf)) # print(score) score.sort(key=lambda x: x[5], reverse=True) # print(score) for h in score: # 输出结果 for j in range(6): print(h[j], end="\t") print() 3、写入文件 # 将结果写入文本score1.txt文件 with open("E:\存/score1.txt", "w") as f1: for h in score: for i in h: f1.write(i + "\t") f1.write("\n") 4、全部代码: with open("E:\存/score.txt", "r", encoding="Utf-8") as f1: txts = f1.readlines() # print(txts)读取文件 score = [] # 添加成绩列 for i in txts: ls = i.split() score.append((i.split())) # print(score) score[0].append("总分") # 第一行的最后一个加上总分 for h in score[1:]: # 将每一行的成绩加到,每一行的总分 zf = float(h[2]) + float(h[3]) + float(h[4]) h.append(str(zf)) # print(score) score.sort(key=lambda x: x[5], reverse=True) # print(score) for h in score: # 输出结果 for j in range(6): print(h[j], end="\t") print() # 将结果写入文本score1.txt文件 with open("E:\存/score1.txt", "w") as f1: for h in score: for i in h: f1.write(i + "\t") f1.write("\n") 5、效果截图

score1.txt文件

控制台效果:

 

四、总结

提示:这里对文章进行总结: 例如:以上就是今天要讲的内容,本文仅仅简单介绍了python的I/O流,读取文件内容、计算学生成绩总分、再写入文件。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3