python - How to do calculations using text files and save the sum on the same text file -
i want calculations using text files , user input, want ask user number minus, want number text file used , minus number user gives , save sum in same text file original number was. problem don't know how this, example have number 13 on text file, user enters 4 sum 9, want 9 saved in same text file number 13 don't know how this. tried using file.write function no success.
i not quite sure how compare values of text file in if/else statement or while statements.
this have done far, apologize might not make sense, need work want work.
number = int(input('please enter number minus')) d = open("numberfile.txt","r+") d.write(int(d.read()) - int(number)) d.close()
whenever run says write argument must in str not int, when change str says operation - not supported.
you should open files with
since handles outmatic file closing etc.
you should try if input of user , of input file convertable int
.
import sys input = input('please enter number minus\n') try: number = int(input) except valueerror e: print('error: ' + str(e)) print('input not integer, ' + str(type(input))) sys.exit(1) io_file = "numberfile.txt" open(io_file,"r") f: input_from_file = f.read() try: number_from_file = int(input_from_file) except valueerror e: print('error: ' + str(e)) print('input not integer, ' + str(type(input_from_file))) sys.exit(1) result = number_from_file - number open(io_file,"w") f: f.write(str(result))
Comments
Post a Comment