Python:如何为两个不同的文本文件执行加法运算符?

时间:2016-01-08 09:25:30

标签: python arrays list numpy addition

我想对两个文件执行添加操作,对于文件A,逐行读取值以便从文件B添加值。如何为文件A逐行启用读取文件?给定文件A和B如下:

A.TXT

2.0 1.0 0.5
1.5 0.5 1.0

B.txt

1.0 1.0 2.0

新文件中的预期输出

3.0 2.0 2.5
2.5 1.5 3.0

示例代码

import numpy as np

with open("a.txt")as g:
    p=g.read().splitlines()
    p=np.array([map(float, line.split()) for line in p])

with open("b.txt")as f:
    x=f.read().splitlines()
    for line in f:
        x=np.array([map(float, line.split()) for line in x])

XP=x+p       
print XP

我还在改进代码。这样做还有其他选择吗?

2 个答案:

答案 0 :(得分:2)

您也可以使用np.loadtxt,例如:

In [11]: import numpy as np
In [12]: A = np.loadtxt('path/to/A.txt')
In [13]: B = np.loadtxt('path/to/B.txt')
In [14]: A + B
Out[14]: array([[ 3. ,  2. ,  2.5], [ 2.5,  1.5,  3. ]])

将结果保存到txt文件同样简单:

In [15]: np.savetxt('path/to/C.txt', A+B)

答案 1 :(得分:2)

from operator import add

b = []

with open("B.txt") as b_file:
    aux = b_file.readline()
    b   = [float(i) for i in aux.split()]

with open("A.txt") as a_file:
    output = open("output.txt", "a")
    for line in a_file:
        aux = [float(i) for i in line.split()]
        res = map(add, aux, b)
        output.write(str(res) + "\n")