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

Python读取多文件并计算每行内容平均值的实现问题

解决Python读取多文件并计算对应行平均值的问题

现有代码

N = [1, 2, 3]
for i in N:
    filepath = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Trials\{}\len_J.py".format(i)
    try:
        with open(filepath, "r") as f:
            content = f.read()
            print(content)
    except FileNotFoundError:
        print("File not found:", filepath)

当前输出

1
2
3

4
5
6

7
8
9

期望输出

4 #(1+4+7)/3
5 #(2+5+8)/3
6 #(3+6+9)/3

改进后的代码

N = [1, 2, 3]
file_data = []
file_count = len(N)

for i in N:
    filepath = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Trials\{}\len_J.py".format(i)
    try:
        with open(filepath, "r") as f:
            # 读取每行并转换为整数,过滤空行
            lines = [int(line.strip()) for line in f if line.strip().isdigit()]
            file_data.append(lines)
    except FileNotFoundError:
        print("File not found:", filepath)
        exit()

# 确保所有文件行数一致
if not all(len(data) == len(file_data[0]) for data in file_data):
    print("所有文件的行数不一致,无法计算平均值")
else:
    # 按行计算平均值并打印
    for row_idx in range(len(file_data[0])):
        total = sum(data[row_idx] for data in file_data)
        avg = total / file_count
        print(f"{int(avg)} #({'+'.join(str(data[row_idx]) for data in file_data)})/{file_count}")

代码说明

  • 用file_data列表存储每个文件的行数据,读取时将每行内容转为整数并过滤空行
  • 提前检查所有文件的行数是否一致,避免计算逻辑出错
  • 遍历行索引,累加对应位置的数值计算平均值,同时按期望格式生成注释并打印结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:22:44