mercredi 6 novembre 2019

Function that extracts random numbers and progressively excludes the ones that generates

I'm trying to do a lottery extractor and i need a script that extracts random numbers and stores the extracted ones to not extract them again.

I came out with the idea of storing the extracted numbers in a text file (ToExclude.txt) and to use the file as "extracted" variable.

I tried doing this without success:

import random

f = open("ToExclude.txt", "r") #Opens the txt in read mode
NumToExclude = f.read() #Stores the txt file (with the previous extracted numbers)
f.close()
open("ToExclude.txt", "w").close() #Erases the content of the file

number = random.randint(1,100) #Random number generator

if number in NumToExclude: #Verifies that the number is not in the Extracted list
    [RESTART FUNCTION] #Restarts the function to generate another number
else:
    NumToExclude.append(number) #If is not in the list add the number to the lsit

print("The number is: {}".format(number)) #Example of output

f = open("ToExclude.txt", "w")  #Stores the extracted number in the txt file
f.write(str(NumToExclude))
f.close()

When i'm executing it the first one goes well, but after the 2nd the text file looks like this:

['[', '5', '7', ',', ' ', '5', '7', ']', 67, 67]



Aucun commentaire:

Enregistrer un commentaire