通过读取文本文件替换Python中的一行

时间:2015-11-02 12:07:08

标签: python

我已经在基于文本的游戏中为玩家位置保存了一个变量。

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 

目前我的加载功能看起来像

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

我知道这是错误的,因为我只学会了如何加载和替换列表。

1 个答案:

答案 0 :(得分:1)

您可以使用“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!"