我的程序是一个基本的Tkinter游戏与记分牌类型系统。此系统将用户名和每个用户的尝试次数存储在文本文件中。你知道吗
例如,当这是用户的第一次时,它会将他们的名字作为[joe\u bloggs,1]附加到文本文件的末尾,其中joe\u bloggs是用户名,1是尝试次数。作为用户的第一次,它是1。你知道吗
我试图寻找一种方法来'更新'或改变数字'1'的增量1每一次。此文本文件以该格式存储所有用户,即[Joe,1][example1,1][example2,2]。你知道吗
以下是我目前拥有的代码:
write = ("[", username, attempts ,"]")
if (username not in filecontents): #Searches the file contents for the username
with open("test.txt", "a") as Attempts:
Attempts.write(write)
print("written to file")
else:
print("already exists")
#Here is where I want to have the mechanism to update the number.
提前谢谢。你知道吗
一个简单的解决方案是使用标准库的^{} 模块:
输出:
下次会议:
输出:
您可以将整个内容转换为字典:
适应您的用例:
如果不想总是检查用户是否已经存在,可以使用
defaultdict
。首先,创建文件:稍后,您只需编写
scores['scores'][user] += 1
:具有多个用户和增量的示例:
输出:
您可以使用标准的ConfigParser模块来持久化简单的应用程序状态。你知道吗
相关问题 更多 >
编程相关推荐