程序运行时出错(Python)

时间:2017-08-13 04:44:17

标签: python

我的程序有问题,是否有人可以帮我修复它?

目的:

在input.txt中:

7 12
100

Output.txt的:

84 16
84是7 * 12,16是100-84

这是我目前的代码:

with open('sitin.txt', 'r') as inpt:
    numberone = inpt.readlines()[0].split(' ') # Reads and splits numbers in the first line of the txt
    numbertwo = inpt.readlines()[1] # Reads the second line of the txt file

product = int(numberone[0])*int(numberone[1]) # Calculates the product
remainder = int(numbertwo)-product # Calculates the remainder using variable seats

with open('sitout.txt', 'w') as out:
    out.write(str(product) + ' ' + str(remainder)) # Writes the results into the txt

它没有输出任何东西。 有人可以帮忙吗? 提前感谢任何人的帮助!

2 个答案:

答案 0 :(得分:0)

考虑发生了什么:

with open('sitin.txt', 'r') as inpt:
    # read *all* of the lines and then take the first one and split it
    numberone = inpt.readlines()[0].split(' ')

    # oh dear, we read all the lines already, what will inpt.readlines() do?
    numbertwo = inpt.readlines()[1] # Reads the second line of the txt file

我确定你可以用这个提示来解决你的家庭作业。

答案 1 :(得分:0)

当您致电inpt.readlines()时,您完全阅读了文件sitin.txt的内容,以便后续调用readlines()将返回空的[]

要避免多次读取时出现此问题,可以在第一次读取时将文件内容保存到变量中,然后根据需要解析不同的行:

with open('sitin.txt', 'r') as inpt:
    contents = inpt.readlines()
    numberone = contents[0].split(' ')
    numbertwo = contents[1]

product = int(numberone[0])*int(numberone[1])
remainder = int(numbertwo) - product

with open('sitout.txt', 'w') as out:
    out.write(str(product) + ' ' + str(remainder))