问题是:
编写一个菜单驱动的Python程序,包括:从用户获取文件名并创建同名文件的函数。然后,函数应该使用while循环来处理文件,并允许用户输入要写入文件的多个整数。
使用for循环读取文件内容并将其输出到屏幕的函数。
向文件中追加若干整数的函数。
计算文件中包含的数字总数并打印
回答屏幕
这是我到目前为止所做的代码,我只需要帮助完成它:def main():
filename = input("Welcom, 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 list
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):
#open file name
outfile = open(filename,"w")
again = "y"
while again == "y":
try:
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 ValueError:
print("An error occured,please enter an integer:\t")
except:
print("An undetermined error occurred")
#close file
outfile.close()
def read(filename):
read(filename)
print("\nReading File)
try:
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):
append(filename)
print("\nAppending to file")
try:
#create file object
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")
except IOError:
print("an error occurred trying to read")
print("the file", filename)
except:
print("an undefined error occurred")
infile.close()
#call main
main()
它一直说,create函数中有一个无效语法。另外,有人能帮我写一个函数,计算文件中包含的数字总数,并将答案打印到屏幕上吗?我正在使用Python3.3.2。
好的,我让代码正常工作了,我只需要编写一个函数来计算文件中包含的数字总数,并将答案打印到屏幕上,如果有人需要帮助,请完成它