Reputation: 41
hiddenWords = ['hello', 'hi', 'surfing']
print("Would you like to enter a new list of words or end the game? L/E?")
decision = input()
if decision == 'L':
print('Enter a new list of words')
newString = input()
newList = newString.split()
hiddenWords.extend(newList)
j = random.randint(0, len(hiddenWords) - 1)
secretWord = hiddenWords[j]
exit(0)
How do I permanently add the input of the user to the hiddenWords list so that next time I open the application the words the user has entered has been extended onto the hiddenWords list?
Thanks. This Code is part of a main body of code.
Upvotes: 3
Views: 4175
Reputation: 1851
I like json. This would be a possible solution:
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
print("added " + add)
except:
print("failed to write file")
If you want to add multiple words at a time use this.
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
save = False
while True:
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
print("added " + add)
save = True
else:
break
if save:
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
except:
print("failed to write file")
Upvotes: 0
Reputation: 59284
When you write
hiddenWords = ['hello', 'hi', 'surfing']
You are, each time the program runs, defining the variable hiddenWords
as ['hello', 'hi', 'surfing']
.
So no matter what you extend after this, every time the code runs the line above, it will redefine to that value.
What you are looking for actually is to use a Database, such as SQLite, to store values so that you can retrieve them at any time. Also, you can save data in a file and read this everytime, which is a simpler way.
Upvotes: 3
Reputation: 1493
When your program exits, all variables are lost, because variables only exit in memory. In order to save your modification accross program executions (everytime you run your script), you need to save the data onto the Disk, i.e: write it to a file. Pickle is indeed the simplest solution.
Upvotes: 1