2016-01-16 57 views
1

我有数千行需要比较的多个文件。 比如我想要做减法file3 = file2 - file1将文件读入数组python

file1 
1 10 5 
2 20 4 
3 30 3 



file2 
5 20 10 
6 30 10 
7 40 10 

file3

4 10 5 
4 10 6 
4 10 7 

我不知道什么是做这种类型的计算最好的方式。我正在尝试Python,但我很难读取文件到python,使其成为适合于计算的数组。 谢谢。

回答

2

你可以使用numpy.genfromtxt

import numpy as np 
a1 = np.genfromtxt('file1') 
a2 = np.genfromtxt('file2') 
a3 = a2 - a1 
print(a3) 
array([[ 4., 10., 5.], 
     [ 4., 10., 6.], 
     [ 4., 10., 7.]]) 

然后,你可以保存阵列numpy.savetxt与格式%d如果需要输出为整数:

np.savetxt('file3', a3, fmt='%d') 
0

打开这两个文件,然后依次通过他们zip

with open('file1.txt') as first, open('file2.txt') as second, open('file3.txt', 'w') as output: 
    for a, b in zip(first, second): 
     a = map(int, a.split()) 
     b = map(int, b.split()) 
     output.write(' '.join(map(str, (y-x for x,y in zip(a,b)))) + '\n')