2017-04-14 30 views
-2

我想使用文本文件和用戶輸入進行計算,我想要求用戶輸入一個減號,然後我想從我的號碼要使用的文本文件,並從用戶給出的編號中減去該文件,並將總和保存在原始編號所在的同一文本文件中。問題是我不知道如何做到這一點,例如我的文本文件中有數字13,比如說用戶輸入4,總和將是9,我希望這9被保存在同一個文本文件中數字13,但我不知道如何做到這一點。我試過使用file.write函數,但沒有成功。如何使用文本文件進行計算並將總和保存在同一文本文件中

我也不太確定如何比較if/else語句或while語句中的文本文件的值。

這是我迄今爲止所做的,我做了道歉,它可能沒有任何意義,我只是需要它像我希望它的工作。

number = int(input('Please enter the number you would like to minus')) 
d = open("numberfile.txt","r+")   
d.write(int(d.read()) - int(number)) 
d.close() 

每當我跑這一點,說寫的參數必須是STR不是整數,但是當我改變它爲str它說,操作 - 不支持。

+0

您需要的數學表達式的結果轉換回一個字符串:'STR(INT(d.read()) - 數字)' – jonrsharpe

+0

還不行,我不斷收到錯誤不受支持操作數 - 對於str和int –

回答

0

你應該總是打開的文件與with因爲這種處理outmatic文件關閉等

你應該嘗試,如果用戶和輸入文件的輸入是可轉換到int

import sys 

input = input('Please enter the number you would like to minus\n') 
try: 
    number = int(input) 
except ValueError as e: 
    print('Error: ' + str(e)) 
    print('Input not a integer, but ' + str(type(input))) 
    sys.exit(1) 

io_file = "numberfile.txt" 
with open(io_file,"r") as f: 
    input_from_file = f.read() 

try: 
    number_from_file = int(input_from_file) 
except ValueError as e: 
    print('Error: ' + str(e)) 
    print('Input not a integer, but ' + str(type(input_from_file))) 
    sys.exit(1) 

result = number_from_file - number 
with open(io_file,"w") as f: 
    f.write(str(result)) 
相關問題