【问题标题】:Python3 - calculate from multiple files and save to new filePython3 - 从多个文件计算并保存到新文件
【发布时间】:2020-09-22 09:25:11
【问题描述】:

我有两个文件:

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')

【问题讨论】:

  • 请在您的问题中包含您的代码。
  • 更新了第一篇文章
  • 你可以使用库吗?还是只是想改进您现有的代码?
  • 我更愿意改进我现有的代码。虽然如果使用一些库会更容易,那么我也可以这样做......

标签: python file math sum save


【解决方案1】:

您需要同时迭代这两个文件。如果您在第一个文件上迭代,然后在第二个文件上迭代,那么您不会同时看到 file1 中的数字与 file2 中的相应数字,因此您无法添加它们。

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 的一些变体:例如参见 Is there a zip-like function that pads to longest length?

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

【讨论】:

  • 谢谢!但是代码的最后一行是:2 + 7 = 27。但它应该是 9。
  • 因为需要int() 铸造,我已经编辑了@fred。顺便说一句,对我来说也是一个很好的解决方案。
  • 谢谢!我之前实际上尝试过 int(),但使用的是:int(a1+a2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2022-01-06
  • 2021-11-09
  • 1970-01-01
  • 2016-07-08
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多