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

问题描述

我有两个文件:

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,int(num2)

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

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)