2017-08-13 71 views
-1

我的程序有问题,是否有人可以帮我修复它?程序运行时出错(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 

它不输出任何内容。 有人可以帮忙吗? 在此先感谢任何人的帮助!

+0

你得到一个错误信息? – BenT

+0

@BenT我怎么看?当我打开它时,该框消失得太快,无法阅读错误消息。 –

回答

0

当你调用inpt.readlines(),你完全通过文件的内容读sitin.txt,使得随后到readlines()调用将返回一个空arrary []

为了避免这个问题多读,你可以将文件内容保存到一个变量上的第一次读,然后分析不同线路需要:

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

我敢肯定,你可以解决你的家庭作业的其余部分与此提示。

+0

Ohhhh!非常感谢! 所以我刚刚添加另一个 与开放('sitin.txt','r')作为inpt 我定义了一个数字之后。 Tysm的帮助! –