读取txt文件并计算每行的平均值并将其写入新文件

时间:2017-12-15 10:13:46

标签: python-3.x

txt文件是这样的。

  

50 70 60

     

40 30 80

     

30 80 40

结果txt文件是这样的。

  

50 70 60 60

     

40 30 80 50

     

30 80 40 50

到目前为止,我确实喜欢这样。但是,我无法获得结果,而且我也无法获得结果。得到平均值

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()

1 个答案:

答案 0 :(得分:1)

我的代码存在问题,因此我尽可能地使用它。

Alamofire.request("https://...",
                   method: .get,
                   parameters: ["myKey1": "myValue1"], 
                   encoding: JSONEncoding.default,
                   headers: self.authHeader).responseJSON { response in 
                        //your response
                   }

评论您的理解。

输出:

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()