Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot write in text file in python program

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone help?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading