任何人都可以幫助我完成此代碼,我需要計算文件中包含的數字的總數,並使用get_total函數將答案打印到屏幕上。我有其他的代碼運行良好我只是不知道如何將數字添加在一起,並顯示答案。我使用python 3.3.2在python中使用獲取總功能
def main():
filename = input("Welcome, please enter file name:\t")
menu()
choice= int(input("Enter menu choice:\t"))
while choice != 5:
#get file choice from user
if choice == 1:
#create file
create(filename)
elif choice == 2:
#read file
read(filename)
elif choice == 3:
#append file
append(filename)
elif choice == 4:
#get total
get_total(filename)
choice = int(input("Enter menu choice:\t"))
print("\nApplication Complete")
def menu():
#user chooses a number from menu
print("Choose a number to continue:\t\n\
Select 1 to create a file\n\
Select 2 to read a file\n\
Select 3 to append to a file\n\
Select 4 to calculate the total of a file\n\
Select 5 to exit programme")
def create(filename):
#create file name
outfile = open(filename,"w")
again = "y"
while again == "y":
try:
#user inputs integer
num = int(input("Input number:\t"))
outfile.write(str(num)+"\n")
#asks user whether they want to continue or not
again = input("Enter y to continue:\t")
#if an error occurs
except ValueError:
print("An error occured,please enter an integer:\t")
except:
print("An undetermined error occurred")
#close file
outfile.close()
def read(filename):
print("\nReading File")
try:
#read integers entered onto file
infile = open(filename,"r")
for line in infile:
number = int(line)
print(number)
except IOError:
print("An error occured trying to read")
print("the file", filename)
except:
print("An undefined error occurred")
def append(filename):
print("\nAppending to file")
#user enters integers again
outfile = open(filename, "a")
again = "y"
while again == "y":
try:
num = int(input("Input number to append to file:\t"))
outfile.write(str(num)+"\n")
again = input ("Enter y to continue:\t")
except ValueError:
print("an error occured please an integer")
except:
print("an undefined error occured")
outfile.close()
def get_total(filename):
print("\nGetting total numbers contained in file")
try:
#user inputs integer
num = int(input("Input number:\t"))
outfile.write(str(num)+"\n")
#asks user whether they want to continue or not
again = input("Enter y to continue:\t")
except IOError:
print("An error occured trying to read")
print("the file", filename)
except:
print("An undefined error occurred")
#call main
main()
感謝您的幫助