我正在制作一个冒险游戏,最后我希望它能打印出来,以便用户回答他们是否喜欢游戏,如果愿意,我希望它在.txt
文件中写下答案。到目前为止,我希望它打开一个.txt
文件并完全写入任何内容,但是不会。它可以单独工作,但是当它放入我的程序时将无法执行。
我尝试移动其位置,尝试尝试if语句和while循环以及效果如何。
import sys
def main():
play_again = True
first_choice = True
fleft_choice = False
fright_choice = False
print_thing = True
while play_again:
print('Welome to my adventure game, would you like to play?')
answer = input()
answer = answer.lower()
if answer == 'yes' or answer == 'y':
print('Fantastic, off we go')
elif answer == 'no' or answer == 'n':
print('Its your choice')
break
else:
print('invalid input')
continue
while first_choice:
print('You come up to a fork in the road. To the left, you hear a battle raging. To the right is winding '
'path that leads to a cave.')
answer1 = input('which do you choose')
if answer1 == "left":
print('you join the fight')
play_again = False
first_choice = False
fleft_choice = True
elif answer1 == 'right':
print('you light a tourch and enter the cave')
play_again = False
first_choice = False
fright_choice = True
else:
print('invalid input')
continue
while fleft_choice:
print('something happens in battle')
fleft_choice = False
while fright_choice:
print('something is in the cave')
fright_choice = False
print('Did you enjoy your adventure?')
yesfile = open("testfile.txt", "w")
yesfile.write('lorem ipsum')
yesfile.close()
print('would you like to play again?')
end_answer = input()
if end_answer == "yes" or end_answer == "y":
main()
if end_answer == 'no' or end_answer == 'n':
sys.exit()
main()
我要弄清楚的是为什么write函数可以单独工作,但是在实现后似乎只是被跳过了。
答案 0 :(得分:0)
您确定您的代码不在函数中间的所有while循环中都处于无限循环中吗? 这是我想到的最明显的原因。
此外,在使用文件时,建议使用以下类型的语法:
content = "test"
with open("file.txt", 'w', encoding="UTF8") as fp:
fp.write(content)
这样,您将永远不会忘记保存文件,但是您的文件也应该可以正常工作。
答案 1 :(得分:0)
您可以尝试将文件打开,写入和关闭操作括在try-catch
块内。返回的错误可以确定问题所在:
try:
yesfile = open(testfile.txt, "w")
yesfile.write(output)
yesfile.close()
except IOError as (number, description):
print("Error({0}): {1}".format(number, description))