[英]Python edit specific words of a text file
My program is a basic Tkinter game with a scoreboard type system. 我的程序是带有记分板类型系统的基本Tkinter游戏。 This system stores the username and the number of attempts each user has had in a text file. 该系统将用户名和每个用户尝试的次数存储在一个文本文件中。
For example, when it is the user's first time, it appends their name to the end of the text file as [joe_bloggs, 1] with joe_bloggs being the username and 1 being the number of attempts. 例如,当它是用户的第一次时,它将其名称作为[joe_bloggs,1]附加到文本文件的末尾,其中joe_bloggs是用户名,1是尝试次数。 As its the user's first time, it's 1. 作为用户的第一次,它是1。
I am trying to look for a way to 'update' or change the number '1' to increment by 1 each time. 我正在尝试寻找一种“更新”或更改数字“ 1”以每次增加1的方法。 This text file stores all the users, ie [Joe,1] [example1, 1] [example2, 2] in that format. 该文本文件以该格式存储所有用户,即[Joe,1] [example1,1] [example2,2]。
Here is the code I currently have: 这是我目前拥有的代码:
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.
Thanks in advance. 提前致谢。
A simple solution would be using the shelve
module of the standard library: 一个简单的解决方案是使用标准库的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()
Output: 输出:
1
2
Next session: 下届会议:
scores = shelve.open('scores')
print(scores['joe_bloggs'])
Output: 输出:
2
A “shelf” is a persistent, dictionary-like object. “架子”是一个持久的,类似于字典的对象。 The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. 与“ dbm”数据库的区别在于,架子中的值(不是键!)本质上可以是任意的Python对象-pickle模块可以处理的任何对象。 This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. 这包括大多数类实例,递归数据类型以及包含许多共享子对象的对象。 The keys are ordinary strings. 键是普通字符串。
You can convert the whole content into a dictionary: 您可以将全部内容转换成字典:
>>> dict(scores)
{'joe_bloggs': 2}
Adapted to your use case: 适应您的用例:
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
If you don't always want to check if the user is already there, you can use a defaultdict
. 如果您不总是想检查用户是否已经在那儿,可以使用defaultdict
。 First, create the file: 首先,创建文件:
from collections import defaultdict
import shelve
with shelve.open('scores', writeback=True) as scores:
scores['scores'] = defaultdict(int)
Later, you just need to write scores['scores'][user] += 1
: 以后,您只需要编写scores['scores'][user] += 1
:
username = 'joe_bloggs'
with shelve.open('scores', writeback=True) as scores:
scores['scores'][user] += 1
An example with multiple users and increments: 一个具有多个用户和增量的示例:
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])
Output: 输出:
joe_bloggs 1
joe_bloggs 2
joe_bloggs 3
user2 1
user2 2
user2 3
您可以使用标准的ConfigParser模块来保留简单的应用程序状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.