Python: 如何对两个不同的文本文件执行加法运算?
Python: How can I perform addition operator for two different text files?
我想对两个文件进行加法运算,对于文件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
我仍在改进代码。还有其他替代方法吗?
也可以使用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)
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")
我想对两个文件进行加法运算,对于文件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
我仍在改进代码。还有其他替代方法吗?
也可以使用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)
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")