簡體   English   中英

通過讀取文本文件替換 Python 中的一行

[英]Replacing a line in Python by reading text file

我在基於文本的游戲中為玩家位置保存了一個變量。

def Save():
    savefile = open('save.txt','w')
    savefile.write(str(currentLocation)+'\n')
    savefile.close()
    print("GAME SAVED!", file=sys.stderr)

這是有效的,文本文件中只有數字 3。

現在我正在嘗試加載該文件以替換我的播放器位置變量中的數字,它看起來像......

currentLocation = 0

因此,在我將文件加載到游戲中后,我希望將 0 替換為文本文件中的數字,以便看起來像。

currentLocation = 3 

目前我的 Load 函數看起來像

def Load():
savefile = open('save.txt', 'r')
for line in savefile:
    currentLocation.append(currentLocation)
savefile.close()

我知道這是錯誤的,因為我只學過如何加載和替換列表。

您可以使用“currentLocation”作為全局變量在加載函數中更改它:

def Load():
    global currentLocation
    with open ("save.txt", "r") as myfile:
        currentLocation = int(myfile.read())
    print "GAME LOADED!"

如果你想加載列表,這取決於你如何保存它們。 一個簡單的可能性是將每個列表條目保存在一個新行中,如下所示:

def saveVisited():
    global visitedLocations
    with open ("save.txt", "w") as myfile:
        for each in visitedLocations:
            myfile.write(str(each) +'\n')
    print("GAME SAVED!")

之后,您可以通過逐行讀取並丟棄'\\n'來讀取列表:

def loadVisited():
    global visitedLocations
    with open ("save.txt", "r") as myfile:
        visitedLocations = [line.rstrip('\n') for line in myfile]
    print "GAME LOADED!"

另一種可能性是例如:

def saveVisited():
    global visitedLocations
    with open ("save.txt", "w") as myfile:
        myfile.write(str(visitedLocations))
    print("GAME SAVED!")

from ast import literal_eval    
def Load():
    global currentLocation
    with open ("save.txt", "r") as myfile:
        currentLocation = list(literal_eval(myfile.read()))
    print "GAME LOADED!"

暫無
暫無

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

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