Python 3.x 读取txt文件并计算每行的平均值,然后将其写入新文件

Python 3.x 读取txt文件并计算每行的平均值,然后将其写入新文件,python-3.x,Python 3.x,txt文件是这样的 507060 40 30 80 308040 结果txt文件如下所示 50706060 40 30 80 50 30804050 到目前为止我确实喜欢这个。但是我不能得到结果,也不能得到平均数 f=open("sample.txt") lines=f.readlines() for line in lines: f2=open("result.txt", 'w') for i in range(len(lines)): each_sco

txt文件是这样的

507060

40 30 80

308040

结果txt文件如下所示

50706060

40 30 80 50

30804050

到目前为止我确实喜欢这个。但是我不能得到结果,也不能得到平均数

f=open("sample.txt")
lines=f.readlines()
    for line in lines:
    f2=open("result.txt", 'w')
    for i in range(len(lines)):
        each_score=line.split()
        f2.write(str(map(int, each_score)))
f.close()
f2.close()

我对你的代码有问题,所以尽我所能使用

f=open("sample.txt")
lines=f.readlines()

f2=open("result.txt", 'w')

for line in lines:
    line = line.strip()
    if line == '':
        continue
    # Set each value as an integer into a list.
    each_score = [int(num) for num in line.split()]
    # Get average from sum/length.
    avg = int(sum(each_score) / len(each_score))
    # Create output list with item as str and include avg.
    output = [str(item) for item in (each_score + [avg])]
    # Finally write the line by joining the values.
    f2.write(' '.join(output) + '\n')

f.close()
f2.close()
为您的理解发表了评论

输出:

50 70 60 60
40 30 80 50
30 80 40 50