Python edit specific text file words

My program is a basic Tkinter game with a scoreboard type system. This system saves the username and the number of attempts that each user has in a text file.

For example, when he is the first user, he adds his name to the end of the text file as [joe_bloggs, 1], and joe_bloggs is the username, and 1 is the number of attempts. As a user, the first time, he is 1.

I am trying to find a way to “update” or change the number “1” to increase by 1 each time. All users are stored in this text file, that is, [Joe, 1] [example1, 1] [example2, 2] in this format.

Here is the code I 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.

+4
2

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

:

>>> 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
+3
0

Source: https://habr.com/ru/post/1666829/


All Articles