你可以用while循环来实现这一点。只要没有break或sys.exit,它就返回到start,这意味着这里的每一个错误输入。希望这有帮助def read_the_file(output):
while True:
print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
"""
question = raw_input("> ")
reading = output.read()
if question == 'yes'or question == 'Y' or question == 'y':
print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
break # or sys.exit
elif question == 'no' or question == 'N' or question == 'n':
sys.exit[1]
else :
print "wrong input"
read_the_file(output_file)
但我建议你把代码改一下。现在,无论你想不想,每次文件被读取时。你可以在用户说“是”后再这样做。如果使用with语句,则文件将只为以下未指定部分打开。文件在这里被读取。def read_the_file(output):
while True:
print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
"""
question = raw_input("> ")
if question == 'yes'or question == 'Y' or question == 'y':
# Open and read file here
with open(output, 'r') as f:
reading = f.read()
# File is now closed
print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
break # or sys.exit
elif question == 'no' or question == 'N' or question == 'n':
sys.exit[1]
else :
print "wrong input"
read_the_file(output_file)