1

I want to write all the Game.py console outputs to a new file every time its ran.

In my Game.py I run all the methods of my game through this

Game.py file:

class Game():
    def play():
        print("Some Text")


if __name__ == "__main__":
    game = Game()
    game.play()

Just for clarity what I want is for the printed text to be saved to a .txt file.

game1.txt would have this inside Some Text

I looked at some code before but I can't get my head around it, how would I do this with stdout?

Tech_Noob
  • 13
  • 3

1 Answers1

0

Got it.

class Game():
    def play():
        f = open("myfile.txt","w+")
        f.write("Some Text")
        # if you still want to print it
        print("Some Text")

if __name__ == "__main__":
    game = Game()
    game.play()

Try to do that. If this works, then this is the answer. If this does not work, tell me.

I am writing myfile.txt with open() and a w+ to write. Then I write in that what you want to write using f.write() and also a extra print() if you need it.


EDIT: Actually, if you have prints in multiple classes, try to open myfile.txt first and remember for the Game class to be the main class otherwise it will fail.

new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34
  • Not "it" to be exact. So when ran in console this will print Some Text and also create a file with only some text, now lets say I have many prints throughout my whole programme it wouldn't be very efficient to have to do this every time unless it does ofc... so I need something to intercept each print and then write it to file. – Tech_Noob Aug 16 '19 at 02:45
  • Well, if that's the case, I don't know, what about combining the prints to 1 single line? – new Q Open Wid Aug 16 '19 at 02:47
  • Wouldn't work if I have prints in other classes I don't think, still not a bad answer if I were to be printing one or a couple lines but not all throughout my programme. This is something Like Logging I guess but logging prints and anything else to a file exactly as it appears when ran in console. – Tech_Noob Aug 16 '19 at 02:49