# 输入文件:
# 三列:学号,姓名,成绩 (用逗号隔开) ,行之间用\n换行分割
#处理:读取文件,按成绩倒序排序
#输出:排序后的三列数据
def read_file():
result = []
with open("./student_score", encoding="utf-8") as fin: # 读取文件,encoding="utf-8"用于解决乱码
for line in fin: # 读取每一行
line = line[:-1] # 去除最后一个换行符
result.append(line.split(","))
return result
def sort_grades(datas):
return sorted(datas,
key=lambda x: int(x[2]),
reverse=True)
def write_file(datas):
with open("./student_score_output", "w", encoding="utf-8") as fout:
for data in datas:
fout.write(",".join(data) + "\n") # 以逗号作为分隔,写出文件
# 读取文件
datas = read_file()
print("读取文件结果为:", datas)
# 排序数据
datas = sort_grades(datas) # 传进去,返回一个排序后的数据
print("降序后的结果为:", datas)
# 写出数据
write_file(datas)