简体   繁体   中英

Python edit specific words of a text file

My program is a basic Tkinter game with a scoreboard type system. 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. As its the user's first time, it's 1.

I am trying to look for a way to 'update' or change the number '1' to increment by 1 each time. This text file stores all the users, ie [Joe,1] [example1, 1] [example2, 2] in that format.

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:

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. 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 . 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 :

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模块来保留简单的应用程序状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM