如何将python程序的输出复制到文本文件? (无法使用控制台,只能使用 Python IDLE)

问题描述 投票:0回答:0

我希望我的程序在 python IDLE 中执行,然后最后的输出必须保存在文本文件中。 这是我的代码: `同时(真): 随机导入 导入时间

#Introduction
print("""                                            You are in the Kingdom of Dragons. In front of you, you see two caves. In one
                                            cave, the dragon is friendly and will share his treasure with you. The other
                                                           dragon is hungry and will eat you on sight!
                                                           

“”)

#letting the player input 1 or 2
while True:
    select = input("cave 1,2,3,4 or 5 : ")
    if (select=="1") or (select=="2") or (select=="3") or (select=="4") or (select=="5"):
        break

#some statements of the game
print("""\nYou approach the cave...""",select)
time.sleep(2)
print("""A large dragon jumps out in front of you!""")
time.sleep(1.5)
print("""He opens his jaws and ...""")

time.sleep(3)

#luck
choices = ["Gobbles you down!","Greets you before share his teature"]
print("\n",random.choice(choices))

time.sleep(2)

again = input("\nDo you wanna play again?(y/n)")
if again=="y":
    continue
else:
    break`

我想把这个游戏在空闲状态下的最后输出保存在一个文本文件中。它必须使用一些源代码来完成。 (不是手动)

我确实尝试了很多堆栈溢出的方法,但这些都不是解决方案。 我使用的方法不适用于我的程序:

  1. `导入 io 导入系统

def foo(): 打印(“你好世界,还有什么?”)

stream = io.StringIO() sys.stdout = 流 尝试: 富() 最后: sys.stdout = sys.stdout

打印(stream.getvalue())`

  1. `# 以写入模式打开文件 打开('lastgame.txt','w')作为文件:

    # Redirect the output to the file
    sys.stdout = file`
    

"""然后是我的程序"""

# Reset the output to the console sys.stdout = sys.__stdout__

还有更多关于堆栈溢出的信息。

我想要我的程序的“最后输出”(不是其他的,只有我最后执行的输出)也在 IDLE 中执行,然后将其保存在文本文件中。(不是手动,不使用控制台,仅在 python IDLE 上)

python python-3.x output text-files python-idle
© www.soinside.com 2019 - 2024. All rights reserved.