【问题标题】:How to replace strings in a text file using Python?如何使用 Python 替换文本文件中的字符串?
【发布时间】:2021-02-08 00:12:02
【问题描述】:

我是一名编程新手,我正在尝试创建一个基于文本的小型游戏,具有高分功能。游戏很好,但是如果玩家在游戏结束时获得更高的分数,我在尝试替换文件中的最高分时会遇到问题。

如果文件不存在,我创建了一个函数来生成文件:

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

所以现在 highscore.txt 文件有两行:

normal null 0
expert null 0
  • 正常/专家 = 玩家选择的游戏模式,我将游戏模式放在变量“模式”中
  • null = 替换为玩家名称,我将玩家名称放入变量“玩家”中
  • 0 = 替换为新的高分,我把分数放在变量“score”中

我尝试创建一个代码,使用 split() 将每行中的每个单词拆分为一个列表,然后检查是否存在玩家获得的分数高于任一模式的当前分数的情况。我的代码:

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()

因此,如果名为“Raka”的玩家在专家模式中获得 20 分,highscore.txt 文件应更改为:

normal null 0
expert Raka 20

遗憾的是,我的代码没有执行任何操作,highscore.txt 的内容保持不变。我尝试调整我的代码,直到现在我还没有找到解决方案。我认为我的代码确实检测到玩家是否获得了新的高分,因为“NEW HIGHSCORE”被打印出来,但文本没有被替换。我希望你们能帮助我。另外,很抱歉我的英语不好,因为它不是我的第一语言。谢谢!

【问题讨论】:

  • 你永远不会向文件中写入内容,这就是它不会改变的原因。

标签: python if-statement text replace


【解决方案1】:

我做了一个简单的脚本来写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()

【讨论】:

  • 谢谢!您的代码在稍微调整后也可以工作。干杯伙伴!
【解决方案2】:

尝试使用以下代码:

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()

我建议在打开文件后将数据存储在一个新变量中,而不是直接访问它,这样可以更轻松地对其进行逻辑处理并提高代码的可读性。此外,每次创建文件处理程序时尝试使用不同的变量名。至于为什么您的代码不起作用,我认为是因为您在替换内容后没有使用checkline.close() 关闭文件。除非您关闭文件,否则程序不会将数据从缓存推送到磁盘,并且内容将保持不变。或者,您也可以使用flush(在您的情况下为checkline.flush())方法将数据推送到文件中,但请记住,这样做时,文件处理程序将继续在后台运行并占用内存,而关闭函数将终止它。内存现在可能不是问题,但在大型项目中可能很重要,这是一种很好的做法。

【讨论】:

  • 哎呀!我忘了把缩进和 close() 函数放在帖子里,但实际上我的代码中有这两个。我已经编辑过了,谢谢指出!感谢您的建议,我仍在学习 Python 中的文本文件,所以我仍然不知道如何实现它。你知道为什么我的代码不起作用吗?谢谢!
  • 首先,有一种更简单的方法可以检查文件是否存在,os.path.isdir(file_path)。其次,如果您以“w”(写入模式)打开一个尚不存在的文件,python 将为您创建一个文件。让我看看剩下的。
  • 谢谢!我尝试使用“w”,但我应该将 highscore.txt 中的分数与玩家获得的最新分数进行比较。使用“w”只会删除 highscore.txt 文件,然后我就没有任何东西可以比较最新的分数了。但也许你在谈论我仍然不明白的“w”的不同实现。你有我可以和你交谈的 Discord 吗?非常感谢您的帮助。
  • 我已经编辑了我的答案,请参考。我关于“​​w”的观点是,您检查文件是否存在的功能似乎是多余的。我很想通过 Discord 讨论这个问题,请随时联系我。不和谐:purujit.kulshreshtha#4549
  • 我实际上是通过调整您的代码找到了答案,非常感谢!我已将你添加到 Discord。
猜你喜欢
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多