我想读取文件并写入另一个文件。基本上,我想做一些算术并写几个其他列

时间:2016-12-06 20:14:16

标签: python-3.x file-io

我有一个像

这样的文件
2.0 4 3
0.5 5 4
-0.5 6 1
-2.0 7 7
.......

实际文件非常大

我想阅读并添加几列,首先添加了列column(4) = column(2) * column(3),添加的第二列将是column 5 = column(2)/column(1) + column(4)所以结果应为

2.0 4 3 12 14
0.5 5 4 20 30
-0.5 6 1 6 -6
-2.0 7 7 49 45.5
.....

我想在另一个文件中写。

with open('test3.txt', encoding ='latin1') as rf: 
     with open('test4.txt', 'w') as wf:
        for line in rf:
            float_list= [float(i) for i in line.split()]
            print(float_list)

但到目前为止我只是有这个。我只能创建列表,不知道如何在列表上执行算术并创建新列。我想我完全不在这里了。我只是python的初学者。任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

我会重用你的公式,但转移索引,因为它们在python中从0开始。 我会使用新计算扩展读取column浮点数列表,并回写行,空格分隔(在列表解析中转换回str

因此,循环的内部部分可以写成如下:

with open('test3.txt', encoding ='latin1') as rf:
     with open('test4.txt', 'w') as wf:
        for line in rf:    
           column= [float(i) for i in line.split()]  # your code
           column.append(column[1] * column[2])  # add column
           column.append(column[1]/column[0] + column[3])  # add another column
           wf.write(" ".join([str(x) for x in column])+"\n")  # write joined  strings, separated by spaces

答案 1 :(得分:0)

这样的事情 - 请参阅代码中的注释

with open('test3.txt', encoding ='latin1') as rf: 
     with open('test4.txt', 'w') as wf:
        for line in rf:
            float_list = [float(i) for i in line.split()]

            # calculate two new columns
            float_list.append(float_list[1] * float_list[2])
            float_list.append(float_list[1]/float_list[0] + float_list[3])

            # convert all values to text
            text_list =  [str(i) for i in float_list]

            # concatente all elements and write line
            wf.write(' '.join(text_list) + '\n')

答案 2 :(得分:0)

尝试以下方法:

map()用于将列表中的每个元素转换为float,最后再次使用它将每个float转换为str,以便我们可以将它们连接起来

with open('out.txt', 'w') as out: 
    with open('input.txt', 'r') as f:
        for line in f:
            my_list = map(float, line.split())
            my_list.append(my_list[1]*my_list[2])
            my_list.append(my_list[1] / my_list[0] + my_list[3])
            my_list = map(str, my_list)
            out.write(' '.join(my_list) + '\n')