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

如何读取TXT文件生成商品行金额文件并计算总求和

问题修正与需求实现

原代码存在的问题

  • 变量名拼写错误:rivi应为row,tiedosto应为file
  • 数据类型错误:价格是浮点数值,用int()转换会丢失精度,需改用float()
  • 列表操作错误:应向定义的list列表添加数据,而非调用file.append(info)
  • 文件操作不规范:未使用上下文管理器with,易导致文件未正常关闭
  • 未实现生成newfile.txt及计算总和的核心需求

修正后的完整实现代码

class DATA:
    def __init__(self):
        self.product = ""
        self.amount = 0
        self.price = 0.0
        self.total = 0.0

def read_and_calculate(name):
    data_list = []
    # 读取原始文件并计算每行总价
    with open(name, 'r', encoding="UTF-8") as file:
        # 跳过表头行
        next(file)
        for row in file:
            row = row.strip()
            if not row:
                continue
            columns = row.split(';')
            info = DATA()
            info.product = columns[0]
            info.amount = int(columns[1])
            info.price = float(columns[2])
            info.total = info.amount * info.price
            data_list.append(info)
    
    # 生成newfile.txt文件
    with open('newfile.txt', 'w', encoding="UTF-8") as new_file:
        for item in data_list:
            # 格式化保留两位小数
            new_file.write(f"{item.total:.2f}\n")
    
    # 计算所有值的总和
    total_sum = sum(item.total for item in data_list)
    return total_sum

# 执行函数并输出结果
final_sum = read_and_calculate('products.txt')
print(f"newfile.txt中所有值的总和为:{final_sum}")

代码说明

  1. 类的修正:将类属性改为实例属性,通过__init__方法初始化,避免类属性被所有实例共享的问题
  2. 文件读取优化:使用with语句自动管理文件生命周期,无需手动关闭;用for循环遍历文件行,比while逻辑更简洁
  3. 数据处理:
    • 用strip()去除每行首尾空白字符(包括换行符)
    • 价格转换为float类型,保证计算精度
    • 总价计算后格式化保留两位小数写入新文件
  4. 总和计算:通过生成器表达式直接从数据列表中求和,高效简洁

执行结果

运行代码后,生成的newfile.txt内容为:

30.00
5.00
6.00
80.00
32.00

控制台输出:

newfile.txt中所有值的总和为:153.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:21:51