将文件读入数组python

时间:2016-01-16 22:04:36

标签: python arrays

我有多个文件需要比较数千行。 例如,我想做减法file3 = file2 - file1

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 个答案:

答案 0 :(得分:2)

您可以使用numpy.genfromtxt

"RuntimeError: 
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.

            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:

                if __name__ == '__main__':
                    freeze_support()
                    ...

            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable."

如果您需要输出为整数,那么您可以使用格式为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.]]) 的{​​{3}}保存该数组:

%d

答案 1 :(得分: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')