2017-08-13 74 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的幫助! –