将控制台输出打印到文本文件

Print console output to text file

import random
import time
import sys


# variable declaration

user_cave=0
cave=0
result=""
playagain="Y"

while playagain=="Y" or playagain=="y":
    fo=open("save_game",'w')

    print("\nYou are in the Kingdom of Dragons.\nIn front of you, you see two caves.\nIn one cave, the dragon is friendly and will share his treasure with you.\nThe other dragon is hungry and will eat you on sight!\nGood luck on your journey\n")
    while True: # including while true because program should till break

        try: # repeat till user give correct value
            user_cave=int(input("Please select cave 1,2,3,4 or 5 : "))
            if user_cave>0 and user_cave<6:
                break

            else:
                continue

        except:
            ""
        

    #create random number to differentiate
    cave=random.randrange(1,3)

    # Bad dragon
    if cave==1:
        result="Gobbles you down!"
    # Good Dragon
    elif cave==2:
        result="Greets you before share his treasure!"

    print("\nYou approach the cave....",user_cave)
    time.sleep(1.5)
    print("A large dragon jumps out in front of you!")
    time.sleep(1.5)
    print("HE OPENS HIS JAWS AND.....\n")
    time.sleep(2)
    print(result,"\n")

    playagain=input("Do you want to play again ? [y/n] : ")

sys.stdout = open("File location",'w')

sys.stdout.close()

我想将所有打印语句输出打印到一个文本文件中。如果用户选择在不关闭程序的情况下再次玩游戏,则需要附加文件,但如果用户关闭并再次运行程序,则需要用新输出覆盖文件。

我认为是,创建一个新文件名xx_time每场比赛

now_time = time.strftime("_%Y_%m_%d_%H_%M_%S]", time.localtime())
# All info about the game is contained in this file
file_path = os.path.join("/your_folder", "game_file{}.txt".format(now_time))

创建一个函数来打印信息并将其写入 txt 文件

def print_and_write(file_object, info):
    print(info)
    file_object.write(info)

如果你想把所有的打印语句都保存到一个文本文件中,你可以把你想保存在文件中的东西复制到一个变量中,然后写到文本文件中。例如,我将您的代码编辑为:

import time
import sys

# variable declaration

user_cave = 0
cave = 0
result = ""
playagain = "Y"

while playagain == "Y" or playagain == "y":
    f = open("Dragon Game.txt", 'w')
    f.write("")
    print(
        "\nYou are in the Kingdom of Dragons.\nIn front of you, you see two caves.\nIn one cave, the dragon is friendly and will share his treasure with you.\nThe other dragon is hungry and will eat you on sight!\nGood luck on your journey\n")
    while True:  # including while true because program should till break

        try:  # repeat till user give correct value
            user_cave = int(input("Please select cave 1,2,3,4 or 5 : "))
            if user_cave > 0 and user_cave < 6:
                break

            else:
                continue

        except:
            ""

    # create random number to differentiate
    cave = random.randrange(1, 3)

    # Bad dragon
    if cave == 1:
        result = "Gobbles you down!"
    # Good Dragon
    elif cave == 2:
        result = "Greets you before share his treasure!"
    txt = f"\nYou are in the Kingdom of Dragons.\nIn front of you, you see two caves.\nIn one cave, the dragon is friendly and will share his treasure with you.\nThe other dragon is hungry and will eat you on sight!\nGood luck on your journey\nYou approach the cave....{str(user_cave)}\nA large dragon jumps out in front of you!\nHE OPENS HIS JAWS AND.....\n{result}"
    f = open("Dragon Game.txt", "a")
    f.write(txt)
    print("\nYou approach the cave.... " + str(user_cave))
    time.sleep(1.5)
    print("A large dragon jumps out in front of you!")
    time.sleep(1.5)
    print("HE OPENS HIS JAWS AND.....\n")
    time.sleep(2)
    print(result, "\n")

    playagain = input("Do you want to play again ? [y/n] : ")

只是,在运行创建这个文件之前,你必须创建一个名为Dragon Game.txt的文件运行代码是必须的。