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

Python读取文本文档数值求和计算平均值报ValueError错误

报错根因

抛出ValueError: invalid literal for int() with base 10: ''的直接原因是循环读到文件末尾时,readline()会返回空字符串'',代码没有做判断就直接尝试把空字符串转成整数,触发类型转换错误。
除此之外原代码还有3个逻辑错误:

  • 漏读第一行数据:进入循环前已经读了第一行,循环内第一句又执行读行操作,第一行的数值完全没参与计算
  • 累加逻辑错误:定义了scoreTotal变量存总分但从未使用,循环内total = int(line) + int(line)是把同一行的数值重复加两次,而且每次循环都会覆盖total的值,根本无法得到所有数值的总和
  • 计数逻辑错误:初始计数器设为1,且不管读到的是不是有效数值都给计数器加1,最终统计的数值数量和实际不符
修正后可运行代码
def CalcAverage():
    # 初始化计数器、总分,初始值都设为0
    scoreCounter = 0
    scoreTotal = 0
    scoresFile = open("data.txt", "r")
    while True:
        line = scoresFile.readline()
        # 读到文件末尾就退出循环
        if not line:
            break
        # 去掉每行首尾的换行、空格,空行直接跳过
        clean_line = line.strip()
        if not clean_line:
            continue
        # 转成整数后累加,计数器+1
        score = int(clean_line)
        scoreTotal += score
        scoreCounter += 1
    scoresFile.close()
    # 处理文件无有效数值的边界情况,避免除以0报错
    if scoreCounter == 0:
        print("文件内没有可计算的有效数值")
        return
    average = scoreTotal / scoreCounter
    print(f"数值总和:{scoreTotal}")
    print(f"有效数值数量:{scoreCounter}")
    print(f"平均值:{average}")

# 调用函数
CalcAverage()
更稳妥的写法优化

用with语句打开文件不需要手动调用close(),哪怕代码运行中途报错也能自动释放文件资源,写法更简洁安全:

def CalcAverage():
    scoreCounter = 0
    scoreTotal = 0
    with open("data.txt", "r", encoding="utf-8") as scoresFile:
        for line in scoresFile:
            clean_line = line.strip()
            if not clean_line:
                continue
            scoreTotal += int(clean_line)
            scoreCounter += 1
    if scoreCounter == 0:
        print("文件内没有可计算的有效数值")
        return
    average = scoreTotal / scoreCounter
    print(f"总和:{scoreTotal},数量:{scoreCounter},平均值:{average}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 01:06:26