gpt4 book ai didi

Python 中的文件写入不会立即发生(刽子手游戏)

转载 作者:行者123 更新时间:2023-11-30 22:43:16 24 4
gpt4 key购买 nike

我刚刚开始为刽子手游戏编写 Python 代码,并将单词存储在文件中。我还提供了一个根据用户意愿添加单词的选项。我已经编写了相同的代码,但由于某种原因,文件在重新启动程序之前不会更新。请告诉我我哪里出错了,我也碰巧有很长一段时间后才开始使用Python编程,所以请记住,这可能是由于生锈或内存故障引起的错误。这是我的代码(仅涉及文件输入输出问题):

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()

最佳答案

Python 文件对象缓冲写入操作,直到达到缓冲区大小。为了将缓冲区实际写入文件,如果要继续写入,请调用 flush() ;如果已完成,请调用 close() :

wordlist.write("foo")
wordlist.flush() # "foo" will be visible in file
wordlist.close() # flushed, but no further writing possible

或者,您可以open the file unbuffered 。这样,所有写入都将立即提交:

wordlist = open('file.txt', buffering=0)

关于Python 中的文件写入不会立即发生(刽子手游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com