You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何write()仅输出最后一行?Python成绩统计代码求助

问题描述

我需要实现以下功能:打开用户输入的TSV文件,输出每位学生的成绩(含等级),以及三门考试的平均分:

  • 期中考试1
  • 期中考试2
  • 期末考试

但实际运行时遇到两个问题:

  1. 写入输出文件后,文件只保留最后一行学生数据
  2. 手动添加的\n换行符完全不起作用

以下是我写的代码:

sum = 0
sum3 = 0
sum2 = 0
n = []
# TODO: Read a file name from the user and read the tsv file here.
file = input()
with open(file) as f:
    data = f.readlines()

# TODO: Compute student grades and exam averages, then output results to a text file here.
with open('report.txt', 'w') as output:
    for line in data:
        split_line = line.split('\t')
        sum1 = int(split_line[2]) + int(split_line[3]) + int(split_line[4])
        avg = sum1 / 3
        # TODO: Compute student grades and exam averages, then output results to a text
        # file here.
        for i in data:
            if avg >= 90:
                split_line.append('A'+'\n')
            if 80 <= avg < 90:
                split_line.append('B'+'\n')
            if 70 <= avg < 80:
                split_line.append('C'+'\n')
            if  60 <= avg < 70:
                split_line.append('D'+'\n')
            if avg < 60:
                split_line.append('F'+'\n')
            break
        for j in data:
            sum += int(split_line[2])
            avg = sum/len(data)
            break
        for k in data:
            sum3 += int(split_line[3])
            avg1 = sum3/len(data)
            break
        for l in data:
            sum2 += int(split_line[4])
            avg2 = sum2/len(data)
            break
    for i in data:
        output.write(str(split_line))

问题分析与修复

核心问题点

  1. 写入逻辑错误:写入文件的循环放在了学生数据处理循环之外,且每次处理学生时都会覆盖split_line变量,最终只写入了最后一次处理的那行数据。
  2. 格式输出错误:直接将split_line列表转成字符串写入,会输出类似['xxx', 'yyy', 'A\n']的格式,\n被当成普通字符而非换行符。
  3. 平均分计算冗余:使用多个无意义的for ... break循环,完全没必要,直接累加分数即可。

修复后的代码

# 初始化三门考试的总分变量
mid1_total = 0
mid2_total = 0
final_total = 0

# 获取文件名并读取内容
file_name = input()
with open(file_name, 'r') as f:
    # 读取所有行,若文件第一行是表头则用[1:]跳过,否则直接用data = f.readlines()
    data = f.readlines()[1:]
    student_num = len(data)

# 生成报告文件
with open('report.txt', 'w') as output:
    # 先写入学生成绩列表
    output.write("学生成绩报告\n")
    output.write("====================\n")
    for line in data:
        line = line.strip()
        if not line:
            continue
        parts = line.split('\t')
        # 提取分数并转换为整数
        mid1 = int(parts[2])
        mid2 = int(parts[3])
        final = int(parts[4])
        # 累加总分
        mid1_total += mid1
        mid2_total += mid2
        final_total += final
        # 计算学生平均分并确定等级
        student_avg = (mid1 + mid2 + final) / 3
        if student_avg >= 90:
            grade = 'A'
        elif 80 <= student_avg < 90:
            grade = 'B'
        elif 70 <= student_avg < 80:
            grade = 'C'
        elif 60 <= student_avg < 70:
            grade = 'D'
        else:
            grade = 'F'
        # 格式化写入一行学生信息,确保换行生效
        output.write(f"{parts[0]}\t{parts[1]}\t平均分:{student_avg:.1f}\t等级:{grade}\n")
    
    # 写入三门考试的平均分
    output.write("\n考试平均分统计\n")
    output.write("====================\n")
    output.write(f"期中考试1平均分: {mid1_total / student_num:.1f}\n")
    output.write(f"期中考试2平均分: {mid2_total / student_num:.1f}\n")
    output.write(f"期末考试平均分: {final_total / student_num:.1f}\n")

修复说明

  • 将写入操作放到学生数据处理循环内部,每处理一个学生就写入一行,避免数据被覆盖
  • 使用f-string格式化输出内容,确保\n能正常触发换行,同时让输出格式更规整
  • 简化平均分计算逻辑,遍历学生时直接累加各科分数,最后统一计算平均分
  • 增加空行判断,避免处理文件末尾空行导致报错

内容的提问来源于stack exchange,提问作者Tarun REX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:06:20