以下是问题:
编写一个菜单驱动的Python程序,其中包括以下内容;
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
函数outfile.write(str(num)+"\n")
中的语法无效。另外,有人可以帮我编写一个函数来计算文件中包含的数字总数,并将答案打印到屏幕上吗?我正在使用python 3.3.2。
好的,所以我让代码正常工作,我只需要帮助编写一个函数来计算文件中包含的数字总数,并将答案打印到屏幕上以完成它,如果有人想帮忙请
答案 0 :(得分:1)
这个问题在上面的行上是一个微不足道的错字:
num = int(input("Input number:\t")
两个(
但只有一个)
,因此Python认为此表达式会继续显示在下一行,当然,对outfile.write
的调用无法直接跟随{{1}的调用1}}那样,所以它是input
。
这是每个人在Python体验中必须尽早学习的东西:当你在一条线上得到一个难以理解的SyntaxError
时,看看上面的一行,看看你是否错过了SyntaxError
, )
或]
。
与此同时,您可能需要考虑使用更智能的编辑器来匹配括号。