Python3 - 从多个文件计算并保存到新文件

Python3 - calculate from multiple files and save to new file

我有两个文件:

data1.txt

First Second
1 2
3 4
5 6
...

data2.txt

First Second
6 4
3 9
4 1
...

我想将第一个文件中的每个数字添加到第二个文件中的数字。并将输出保存到第三个文件。

这样结果就是:

sum.txt

Sum
7 6
6 13
9 7
....

到目前为止我有这个代码(不工作)

with open('data1.txt') as f1, open('data2.txt') as f2, open('sum.txt', 'w') as f_out:

    f_out.write(f'Sum1 Sum2\n')

    header = next(f1)
    c1, c2 = header.strip().split(' ')

    header = next(f2)
    c1, c2 = header.strip().split(' ')

for line in f1:
    line = line.strip()
    num1, num2 = line.split(' ')
    num1, num2 = int(num1), int(num2)

for line in f2:
    line = line.strip()
    num1, num2 = line.split(' ')
    num1, num2 = int(num1), int(num2)

    sum1 = f1(num1) + f2(num1)
    sum2 = f1(num2) + f2(num2)

    f_out.write(f'{sum1} {sum2}\n')

您需要同时迭代两个文件。如果您对第一个文件进行迭代,然后对第二个文件进行迭代,那么您将无法同时看到文件 1 中的数字和文件 2 中的相应数字,因此您无法添加它们。

with open('data1.txt','r') as f1, open('data2.txt','r') as f2, open('sum.txt', 'w') as f_out:
    h1, h2 = next(f1), next(f2)
    f_out.write(f'Sum1 Sum2\n')
    for line1, line2 in zip(f1, f2):
        a1, b1 = line1.strip().split()
        a2, b2 = line2.strip().split()
        f_out.write('{} {}\n'.format(int(a1)+int(a2), int(b1)+int(b2)))

请注意,如果两个输入文件的行数不同,这可能会或可能不会按您预期的方式运行。修复该行为以更好地满足您需求的一种方法是使用 while 循环并在循环内手动调用 next(f1)next(f2),使用两个 try/except 块捕获异常。另一种方法是使用 zip 的一些变体:例如参见 [​​=15=]

您可以使用 csv 模块打开文件并直接获取列表,而不是在每一行都使用 .strip().split()。 csv 模块的文档:https://docs.python.org/3/library/csv.html