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

Not printing the txt file after program ends

It is opening an txt file and writes what is asked. But does not print the results on the first time.
When I run the program again, then the results that were stored in the txt file from the first run get printed.

Why does it nog print the results from the first run on the first run.

Just starting out.

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

import random

print("======WELCOME TO THE DICE GUESSING GAME=======")
print("Rules of the game : - You can try 3 times!")
print("")
dice = random.randint(1, 6)
guesses = 3`enter code here`
file = open("score.txt", "a")
file.write("Dice number: " + str(dice) + " ")
while guesses > 0:
    guess = int(input("guess the number of the dice: "))
    file.write("guess = " + str(guess) + " ")
    if dice == guess:
        print("That is the correct answer!")
        print("You have won the game!")
        break
    elif guesses != 1:
        print("Try again! You have " + str(guesses - 1) + " chances left, good luck! ")
        guesses -= 1
    else:
        print("You did not guess the correct number!")
        print("The correct number was: " + str(dice))
        break
content = open("score.txt", "r")
read = content.read()
print(read)
file.close()

>Solution :

You need to close the file handle before reading the file back in from the content handle, as file output is buffered.

Here is what the code should look like after the while loop:

file.close()
content = open("score.txt", "r")
read = content.read()
print(read)
content.close()
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