Search code examples
pythontext

my python script prints the same value more times


hi guys i made a script for a game in python (the game is written in python too) that logs all users name that joins in game and saves them in a text file so:

 def onPlayerJoin(self, player):
    'Called for new players joined'
    nick= player.getName(full=True).encode('utf-8')
    #append
    f = open(r"ALLIDS.txt", "a+")
    f.seek(0)
    data = f.read(100)
    if len(data) > 0 :
        f.write("\n")
    f.write(str(nick)+": ")

IT DOESN'T MAKE ANY BUGz AND IT WORKS WELL

OUTPUT OF TEXT FILE

Linux31748: 
JunkieSam: 
Linux31748: 
JunkieSam: 
StratexFsk: 
Linux31748: 
StratexFsk: 
Linux31748: 
DrugrichSam: 
SapoBully: 
Stop Using /GP: 
JunkieSam:

it prints the same player name more times so i want to fix that but i don't know how

thanks in advance for the replies , love this community every day more.


Solution

  • You can check if player already written(also I simplified some of the syntax):

    def log_player(player_nick, file=r"ALLIDS.txt"):
        with open(file, "a+") as f:
            f.seek(0)
            # TODO: improve algorithm, this is just showing the concept
            if player_nick in f.read(): 
                return
            f.write(f'{player_nick}\n')
    
    
    def onPlayerJoin(self, player):
        'Called for new players joined'
        nick = player.getName(full=True).encode('utf-8')
        log_player(nick)
    

    Can you have a try?