如何读取2个txt文件并使用python将结果写入第三个文件

时间:2017-06-24 04:23:13

标签: python

我有3个文件,其中包含以下内容:

today.txt

570

yesterday.txt

500

now.txt

0

基本上,我需要读取前两个文件并将结果写在第三个文件中:

today.txt - yesterday.txt = now.txt(570 - 500 = 70)

2 个答案:

答案 0 :(得分:1)

打开文件进行读取,读取整数,进行数学运算,写回结果

fpToday = open("today.txt", "r")
fpYesterday = open("yesterday.txt","r")
fpNow = open("now.txt","w")
numToday = fpToday.read().rstrip('\n')
numYesterday =fpYesterday.read().rstrip('\n')
numNow = int(numToday) - int(numYesterday)
fpNow.write(str(numNow))
fpToday.close()
fpYesterday.close()
fpNow.close()

答案 1 :(得分:0)

你可以这样做:

`

with open("today.txt", "r") as today:
    with open("yesterday.txt", "r") as yesterday:
        with open("now.txt", "a") as now:
            today = today.read()
            yesterday = yesterday.read()
            result = int(today) - int(yesterday)
            now.write(str(result))
            # TO SEE 'now' FILE
            with open("now.txt", "r") as now:
                print("\n".join(now))

`