Python txt文件,平均值,信息

时间:2014-03-15 16:30:52

标签: python file text average

我有一个.txt文件(它应该是随机名称,tho):

My Name 4 8 7 
Your Name 5 8 7 
You U 5 9 7
My My 4 8 5
Y Y 8 7 9 

我需要将信息放入带有名称+数字平均值的文本文件results.txt中。我该怎么做?

with open(r'stuff.txt') as f:
    mylist = list(f)

i = 0
sk = len(mylist)
while i < sk - 4:
    print(mylist[i], mylist[i+1], mylist[i+2], mylist[i+3])
    i = i + 3

3 个答案:

答案 0 :(得分:3)

首先,打开输入和输出文件:

with open("stuff.txt") as in_file:
    with open("results.txt", "w") as out_file:

由于问题只需要独立地处理每一行,因此对每个line进行简单的循环就足够了:

        for line in in_file:

将空白处的每一行拆分为字符串列表(row):

            row = line.split()

数字出现在前两个字段之后:

            str_nums = row[2:]

但是,这些仍然是字符串,因此必须将它们转换为浮点数以允许对它们执行算术运算。这会产生一个浮点列表(nums):

            nums = map(float, str_nums)

现在计算平均值:

            avg = sum(nums) / len(str_nums)

最后,将名称和平均值写入输出文件。

            out_file.write("{} {} {}\n".format(row[0], row[1], avg))

答案 1 :(得分:1)

这是怎么回事?

with open(fname) as f:
   new_lines = []
   lines = f.readlines()       
   for each in lines:          
     col = each.split()
     l = len(col)#<-- length of each line
     average = (int(col[l-1])+int(col[l-2])+int(col[l-3]))/3
     new_lines.append(col[0]+col[1]+str(average) + '\n')
   for each in new_lines:#rewriting new lines into file 
     f.write(each)
   f.close()

答案 2 :(得分:0)

我试过了,这很有效:

{{1}}