簡體   English   中英

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

[英]How to replace strings in a text file using Python?

我是編程新手,我正在嘗試創建一個具有高分功能的基於文本的小型游戲。 游戲很好,但是如果玩家在游戲結束時獲得更高的分數,我在嘗試替換文件中的高分時遇到了問題。

如果文件不存在,我創建了一個 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

所以現在 highscore.txt 文件有兩行:

normal null 0
expert null 0
  • normal/expert = 玩家選擇的游戲模式,我把游戲模式放在變量“mode”中
  • null = 替換為玩家名,我將玩家名放在變量“player”中
  • 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”后獲得了新的高分,但文本沒有被替換。 我希望你們能幫助我。 另外,抱歉我的英語不好,因為它不是我的母語。 謝謝!

我做了一個簡單的腳本來寫入 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()

嘗試使用以下代碼:

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()關閉文件。 除非您關閉該文件,否則程序不會將數據從緩存推送到磁盤,內容將保持不變。 或者,您也可以使用刷新(在您的情況下為checkline.flush() )方法將數據推送到文件中,但請記住,這樣做時,文件處理程序將繼續在后台運行並在關閉時占用 memory function 將終止它。 Memory 現在可能不是問題,但在大型項目中可能很重要,這是一種很好的做法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM