【问题标题】:How do I open two files and subtract them then store them into a file? [duplicate]如何打开两个文件并减去它们然后将它们存储到一个文件中? [复制]
【发布时间】:2022-01-14 22:25:41
【问题描述】:

我想问一下如何打开两个里面有数据的文件,然后减去它们然后将它们存储到一个文件中?

     with open("bignum.txt","r") as f:
                score=f.read()
                score_ints =[int(x) for x in score.split()]

        with open("smallnum.txt","r")as d:
            score_y = d.read()
            score_y_ints =[int(x) for x in score_y.split()]
        difference = [x - y for x, y in zip(score_ints, score_y_ints) ]

smallnum.txt
10000 120

bignum.txt 99 2220

预期结果: 9901 -2100

这是我之前的代码。它会将其输出为列表,但这不是我想要的。

【问题讨论】:

  • 您能否提供文本文件的示例以及您的预期输出是什么
  • @Tzane 我已将结果附在我的帖子中。谢谢

标签: python python-3.x


【解决方案1】:
with open("f1.txt", "r") as f:
    f1 = f.read()
    f1_ints = [int(x) for x in f1.split()]


with open("f2.txt", "r") as f:
    f2 = f.read()
    f2_ints = [int(x) for x in f2.split()]
    
with open("f1_minus_f2.txt", 'w') as f:
    for i in range( min( len(f1_ints), len(f2_ints)) ) : 
        f.write(str(f1_ints[i] - f2_ints[i]))
        f.write(' ')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多