[英]Python edit specific words of a text file
我的程序是带有记分板类型系统的基本Tkinter游戏。 该系统将用户名和每个用户尝试的次数存储在一个文本文件中。
例如,当它是用户的第一次时,它将其名称作为[joe_bloggs,1]附加到文本文件的末尾,其中joe_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.
提前致谢。
一个简单的解决方案是使用标准库的shelve
模块:
import shelve
scores = shelve.open('scores')
scores['joe_bloggs'] = 1
print(scores['joe_bloggs'])
scores['joe_bloggs'] += 1
print(scores['joe_bloggs'])
scores.close()
输出:
1
2
下届会议:
scores = shelve.open('scores')
print(scores['joe_bloggs'])
输出:
2
“架子”是一个持久的,类似于字典的对象。 与“ dbm”数据库的区别在于,架子中的值(不是键!)本质上可以是任意的Python对象-pickle模块可以处理的任何对象。 这包括大多数类实例,递归数据类型以及包含许多共享子对象的对象。 键是普通字符串。
您可以将全部内容转换成字典:
>>> dict(scores)
{'joe_bloggs': 2}
适应您的用例:
username = 'joe_bloggs'
with shelve.open('scores') as scores:
if username in scores:
scores[username] += 1
print("already exists")
else:
print("written to file")
scores[username] = 1
如果您不总是想检查用户是否已经在那儿,可以使用defaultdict
。 首先,创建文件:
from collections import defaultdict
import shelve
with shelve.open('scores', writeback=True) as scores:
scores['scores'] = defaultdict(int)
以后,您只需要编写scores['scores'][user] += 1
:
username = 'joe_bloggs'
with shelve.open('scores', writeback=True) as scores:
scores['scores'][user] += 1
一个具有多个用户和增量的示例:
with shelve.open('scores', writeback=True) as scores:
for user in ['joe_bloggs', 'user2']:
for score in range(1, 4):
scores['scores'][user] += 1
print(user, scores['scores'][user])
输出:
joe_bloggs 1
joe_bloggs 2
joe_bloggs 3
user2 1
user2 2
user2 3
您可以使用标准的ConfigParser模块来保留简单的应用程序状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.