Python 3.x 使用python从两个不同的文件添加列

Python 3.x 使用python从两个不同的文件添加列,python-3.x,Python 3.x,我试图从不同的文本文件中添加相应的列,但是我只从上一个文件中获取数据。例如,我有两个文件名file1和file2。我想用file2的column1添加file1的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

我试图从不同的文本文件中添加相应的列,但是我只从上一个文件中获取数据。例如,我有两个文件名file1和file2。我想用file2的column1添加file1的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等等,但它没有给出正确的值,因为它做的是累积和。我还附上了该文件的屏幕截图。所有文件都具有相同的格式。

我将下面的代码编写得非常详细,以便您可以确切地看到发生了什么。请随意修改以适合您的用例。这适用于两个文本文件,假设每个文本文件都包含逗号分隔的值

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)

一次只打开一个文件,因此无法执行任何操作。您应该同时打开这两个文件,然后对它们进行操作。我试图在循环中打开它们。当我打开他们的循环。你能告诉我怎么做吗。我必须对21个这样的文件执行这样的操作。请确保您可以在
forloop
中打开所有文件,然后使用它们。ie只是有一个空列表,并将所有文件附加到其中。现在,按照你想要的方式操作所有的值,比如字符串或数字??所有这些都是数字。谢谢Eric,我有了一些想法,但它仍然不能像我想要的那样工作。它将file1第一列的第一个元素添加到file2第一列的所有元素中。我想将file1的第1列的第一个元素添加到file2的第1列的第一个元素,将第二个元素添加到第二个元素,依此类推。还有,当有-ve符号时不起作用。@hemanta不应该有。它们都使用相同的位置变量。当我将一个值设为负值时,我收到了以下错误消息:回溯(最近一次调用):文件“res.py”,第9行,在数据中_1=[int(I[position]),对于文件中的I_1_data]文件“res.py”,第9行,对于文件中的I=[int(I[position]),值错误:对于int()以10为基数:“-”如果我去掉那个-符号,它就会消失。非常感谢。帮了我很多忙。