Python 3.x 我想读一个文件,然后写另一个文件。基本上,我想做一些算术和写几个其他的专栏

Python 3.x 我想读一个文件,然后写另一个文件。基本上,我想做一些算术和写几个其他的专栏,python-3.x,file-io,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('

我有一个像这样的文件

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的初学者。任何帮助都将不胜感激。谢谢

我会重用您的公式,但会移动索引,因为在python中它们从0开始。 我会用新的计算扩展read
浮点数列表,并写回以空格分隔的行(在列表中转换回
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

类似这样的内容-请参见代码中的注释

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')
请尝试以下操作:

用于将列表中的每个元素转换为
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')

行尾有新值,因此将新值附加到列表
float\u list.append()
。然后使用
'.join()
生成行。或者使用带有空格的
csv
模块。@juanpa.arrivillaga:你建议我怎么做?我对python和一般编程都很陌生。如果你能具体一点,那将非常有帮助。谢谢。在python 3中不起作用,因为
map
返回一个迭代器,而不是一个列表。@Jean-Françoisfare python 3在这个问题中没有标记。如果代码是Python3,我认为OP应该指定它。这很有效。我唯一的问题是它会跳过第一行。你对此有何评论?再次感谢!这将消耗第一和第二行。有没有办法不使用任何一行?对不起,我看错了。我不明白为什么它会占用第一行:打开文件,在这些行上迭代。它不会跳过任何一行。这不合逻辑。再次检查您的输入文件。我发现了我的错误。对不起,浪费了你的时间。我在代码中有两次“for line in rf:”。谢谢你的帮助!!!