dimanche 25 octobre 2020

How to replace strings in a text file using Python?

I am a newbie in programming and I'm trying to create a small text-based game with a high score feature. The game is fine, but I have a problem in trying to replace the highscore in the file if the player gets a higher score when the game is finished.

I created a function to make the file if it doesn't exist by using:

def createhighscore(): 
hs = os.listdir()
highscore = None 
if "highscore.txt" not in hs:
    highscore = open("highscore.txt", 'w')
    a = ["normal null 0\n", "expert null 0\n"]
    highscore.writelines(a)
return highscore

So now the highscore.txt file has two lines:

normal null 0
expert null 0
  • normal/expert = the gamemode the player picked, i put the gamemode in the variable "mode"
  • null = replaced with player name, i put the player name in the variable "player"
  • 0 = replaced with the new highscore, i put the score in the variable "score"

I tried creating a code that split each word in each line into a list by using split(), and then checking if there is a condition where the score the player gets is higher than the current score for either mode. My code:

checkline = open("highscore.txt", "r+")
for line in checkline:
   x = line.split()
   if x[0] == mode.lower() and int(x[2]) < score:
       line.replace(x[1], player)
       line.replace(x[2], str(score))
       print("NEW HIGHSCORE")
checkline.close()

checkline = open("highscore.txt", "r+")
for line in checkline:
   x = line.split()
   if x[0] == mode.lower() and int(x[2]) < score:
       x[1] = player
       x[2] = score
       print("NEW HIGHSCORE")
checkline.close()

So if a player with the name "Raka" gets a score of 20 in Expert mode, the highscore.txt file should change to:

normal null 0
expert Raka 20

Sadly my code doesn't do anything and the content of the highscore.txt stays the same. I tried tweaking my code and until now I still haven't found the solution. I think my code does detect if the player gets a new highscore since "NEW HIGHSCORE" gets printed, but the text doesn't get replaced. I hope you guys can help me. Also, sorry for my bad English since it's not my first language. Thanks!

Aucun commentaire:

Enregistrer un commentaire