使用python从两个不同的文件添加列

时间:2018-08-08 15:33:44

标签: python-3.x

我正在尝试从不同的文本文件中添加相应的列,但是我仅从上一个文件中获取数据。例如,我有两个文件,分别为file1和file2。我想将file1的column1与file2的column1相加,依此类推。

[for atom in range(1, 3):
    file = open("filename" + str(atom), "r")
    line = file.split("\n")\[0\]
    col1 = float(line.split()\[1\])
    col2 = float(line.split()\[2\])
    col3 = float(line.split()\[3\])
    total = col1 + col2 + col3
file.close()][1]

我尝试做col1 + = col1,依此类推,但是它没有给出正确的值,因为它累加了总和。我还附加了该文件的屏幕快照。所有文件都具有相同的格式。

1 个答案:

答案 0 :(得分:0)

我使下面的代码非常冗长,因此您可以确切地了解发生了什么。随意修改以适合您的用例。假设两个文本文件都包含逗号分隔的值,则该文件可以使用。

with open('file_1.txt', 'r') as file_1:
    file_1_data = file_1.readlines()

with open('file_2.txt', 'r') as file_2:
    file_2_data = file_2.readlines()

# Position of your column.  Zero is the first column.
position = 0

rows_file_1 = []
negative = False
for row in file_1_data:
    _ = []
    for item in row:
        if item is '-':
            negative = True
        elif item is ',' or item is ' ' or item is '\n':
            pass
        else:
            if negative is True:
                _.append(int(item) * -1)
                negative = False
            else:
                _.append(int(item))
    rows_file_1.append(_)

rows_file_2 = []
for row in file_2_data:
    _ = []
    for item in row:
        if item is '-':
            negative = True
        elif item is ',' or item is ' ' or item is '\n':
            pass
        else:
            if negative is True:
                _.append(int(item) * -1)
                negative = False
            else:
                _.append(int(item))
    rows_file_2.append(_)

print("Each inner array is a row. Values have been converted to integers.")
print(rows_file_1)
print(rows_file_2)

data_1 = [i[position] for i in rows_file_1]
data_2 = [i[position] for i in rows_file_2]

print()
print("Based upon the position, we've pulled out the column values your interested in.")
print(data_1)
print(data_2)

results = [i + ii for i, ii in zip(data_1, data_2)]

print()
print("Sum of each respective item in each file.")
print(results)