I created a simple program that lets you input a set of numbers, then creates a randomly generated list of pairs from the data that was given by the person.
How can I save the data (as a Windows file) once it finishes?
This is my code:
import random as ran
import easygui as eg
nList=vList=eg.multenterbox(msg="Enter the names of the people:"
, title="Random Pair Generator"
, fields=('Name:', 'Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:','Name:',)
, values=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
)
index=0
x=''
y=''
pList=[]
pair=''
while not(index==len(nList)):
x=nList[index]
y=ran.choice(vList)
pair=x+'; '+y
pList.insert(index, pair)
vList.remove(y)
index= index+1
eg.textbox(msg="These are the pairs generated."
, title= "Random Pair Generator"
, text= str(pList)
, codebox=0
)
I just want to save pList as a file, anywhere on my computer (preferably somewhere I can specify).
Also, this loop creates an issue. It doesn’t raise an error with syntax or anything, but the output is not what I want it to be.
What it does is it uses each value from nList, then picks a random value from vList, and then puts those as one object into pList. However, the problem arises that when I have it delete the output of “y” from vList, it also removes it from nList.
Example: If nList contains 5 objects: [1, 2, 3, 4, 5] and vList has the same objects [1, 2, 3, 4, 5]. It would select a random number from vList for every value in nList.
However, once a variable from vList is chosen, it is removed from the list. The problem is that say pList starts as [1; 2] where 1; 2 is one object, the next object would start at 3. It would skip over 2 because 2 was already used as a ‘y’ value.
If you just want to save the list of pairs in the same format as it was displayed in your
eg.textbox, add something like this to end of your program:You could write each pair of the list on a separate line of the output file like this:
Using the
withstatement means the file will be closed for you automatically after the block of code it controls is finished.