Reputation: 19
I just started writing a python code for a hangman game and I'm storing the words in a file. I also have given an option to add words based on users will.I have written the code for the same but for some reason the file is not updated until the program is relaunched.Please tell me where am i going wrong also I happen to have started programming on python after a long time so please keep in mind that it could be a mistake caused due to rustiness or memory faults.Here's my code(only regarding the file input output problem):
import os
def start():
wordlist = open("wordlist_hangman",'a+')
words= wordlist.read()
choice=menu()
if choice=='1':
os.system('cls' if os.name == 'nt' else 'clear')
game_start(wordlist,words)
elif choice=='2':
os.system('cls' if os.name == 'nt' else 'clear')
add_word(wordlist)
elif choice=='3':
os.system('cls' if os.name == 'nt' else 'clear')
print words
start()
else:
os.system('cls' if os.name == 'nt' else 'clear')
print('Invlaid input:must enter only 1,2 or 3 ')
start()
def menu():
print('Enter the number for the desired action.At any point in time use menu to go back to menu.')
print('1.Start a new game.')
print('2.Add words in dictionary.')
print('3.See words present in dictionary')
menu_choice=raw_input('>')
return menu_choice
def add_word(wordlist):
print("Enter the word you wish to add in ypur game")
wordlist.write("\n"+raw_input('>'))
start()
start()
Upvotes: 1
Views: 58
Reputation: 73470
The Python file object buffers the write operations until the buffer size is reached. In order to actually write the buffer to the file, call flush()
if you want to continue writing or close()
if you have finished:
wordlist.write("foo")
wordlist.flush() # "foo" will be visible in file
wordlist.close() # flushed, but no further writing possible
Alternatively, you can open the file unbuffered. That way, all writes will be committed immediately:
wordlist = open('file.txt', buffering=0)
Upvotes: 3