Home > database >  Cannot write in text file in python program
Cannot write in text file in python program

Time:06-29

So I am making a python game and everything in the python programs is fine except for the writing part

Here is a part of GameFile2.py:

class lostToss():

    def botChoose(self):
        print("Bot is choosing between batting and bowling.")
        for dot in range(5):
            print((dot   1) * ".")
            time.sleep(0.25)
        for x in range(10):
            print("")
        choices = ['Bat', 'Bowl']
        botting = random.choice(choices)
        print(f"And the bot has chose to {botting}")
        time.sleep(1)
        if botting == "Bat":
            f = open("GamePoints.txt","w")
            with open('GamePoints.txt, 'a ') as f:
                f.write('52L05yt0smdwPMA4wgdTUF7Yh4dLT')
                print('ok')
                time.sleep(10)
                import GameFile3
        elif botting == "Bowl":
            file = open("GamePoints.txt","w ")
            with open('GamePoints.txt', 'a ') as file:
                file.write('69L05yt0smdwPMA4wgdLOL7Yh4dLT')
                time.sleep(2)
                import GameFile3

The problem is in the 15th and 22nd line, I ran the file many times and the "ok" text was printed but the code couldn't be written in the file.

Can anyone help?

CodePudding user response:

Omit the file opening before the with statements. Like this

f = open("GamePoints.txt","w") # remove this line
with open('GamePoints.txt', 'a ') as f:
file = open("GamePoints.txt","w ") # remove this line
with open('GamePoints.txt', 'a ') as file:

In the first block, you are missing the closing quote after .txt.

  • Related