简体   繁体   English

如何使用 Python 替换文本文件中的字符串?

[英]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:如果文件不存在,我创建了一个 function 来制作文件:

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:所以现在 highscore.txt 文件有两行:

normal null 0
expert null 0
  • normal/expert = the gamemode the player picked, i put the gamemode in the variable "mode" normal/expert = 玩家选择的游戏模式,我把游戏模式放在变量“mode”中
  • null = replaced with player name, i put the player name in the variable "player" null = 替换为玩家名,我将玩家名放在变量“player”中
  • 0 = replaced with the new highscore, i put the score in the variable "score" 0 = 替换为新的最高分,我把分数放在变量“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.我尝试创建一个代码,使用 split() 将每行中的每个单词拆分成一个列表,然后检查是否存在玩家获得的分数高于任一模式的当前分数的情况。 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:因此,如果名为“Raka”的玩家在专家模式中获得 20 分,则 highscore.txt 文件应更改为:

normal null 0
expert Raka 20

Sadly my code doesn't do anything and the content of the highscore.txt stays the same.遗憾的是我的代码没有做任何事情,highscore.txt 的内容保持不变。 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.我认为我的代码确实检测到玩家是否在打印“NEW HIGHSCORE”后获得了新的高分,但文本没有被替换。 I hope you guys can help me.我希望你们能帮助我。 Also, sorry for my bad English since it's not my first language.另外,抱歉我的英语不好,因为它不是我的母语。 Thanks!谢谢!

I made a simple script to write the changes in the highscores.txt, even if there are no changes the text file is overwritten.我做了一个简单的脚本来写入 highscores.txt 中的更改,即使没有更改文本文件也会被覆盖。

score = 30
mode = "normal"
player = "Raka"

f = open("highscore.txt", "r")
lines = f.read().split("\n")
#remove empty lines in the lines list
lines = [line for line in lines if line.strip() != ""]
for x in range(0, len(lines)):
    words = lines[x].split(" ")
    if words[0] == mode and score > int(words[2]):
        lines[x] = mode +" "+player+" "+str(score)


#Write the changes in highscore.txt
outF = open("highscore.txt", "w")
for line in lines:
  outF.write(line)
  outF.write("\n")
outF.close()

Try using the following code:尝试使用以下代码:

check_high_score = open("highscore.txt", "r")
list_high_scores = check_high_score.readlines()
check_high_score.close()

to_write = []

for score in list_high_scores:
    if mode.lower() == "normal":
        if int(list_high_scores[0][2]) < score:
            to_write.append("normal " + player + " " + str(score))
        else:
            to_write.append(list_high_scores[0])
    elif mode.lower() == "expert":
        if int(list_high_scores[1][2]) < score:
            to_write.append("expert " + player + " " + str(score))
        else:
            to_write.append(list_high_scores[1])
        
write_score = open("highscore.txt", "w")
write_score.writelines(to_write)
write_score.close()

I'd recommend storing the data in a new variable after opening a file rather than directly accessing it, makes it easier to logic on it and improves the code readability.我建议在打开文件后将数据存储在一个新变量中,而不是直接访问它,这样更容易对其进行逻辑处理并提高代码的可读性。 Also, try to use different variable names each time you make a file-handler.另外,每次创建文件处理程序时尝试使用不同的变量名。 As to why your code is not working, I think it's because you haven't closed the file with checkline.close() after replacing the contents.至于为什么你的代码不起作用,我认为这是因为你在替换内容后没有用checkline.close()关闭文件。 Unless you close the file, the program will not push the data from the cache to the disk and the contents will remain the same.除非您关闭该文件,否则程序不会将数据从缓存推送到磁盘,内容将保持不变。 Alternatively, you can also use the flush ( checkline.flush() in your case) method to push the data into the file but keep in mind, in doing so, the file handler will keep running in the background and take memory while the close function will terminate it.或者,您也可以使用刷新(在您的情况下为checkline.flush() )方法将数据推送到文件中,但请记住,这样做时,文件处理程序将继续在后台运行并在关闭时占用 memory function 将终止它。 Memory may not be a problem now but can be important in larger projects and it's good practice. Memory 现在可能不是问题,但在大型项目中可能很重要,这是一种很好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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