简体   繁体   中英

Replacing a line in Python by reading text file

I have saved a varible in my text based game for the players position.

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

This works and the text file only has the number 3 in it.

Now I am trying to load that file to replace the number in my player position varible which looks like...

currentLocation = 0

So after I load the file into the game I want the 0 to be replaced with the number from the text file so it will look like.

currentLocation = 3 

Currently my Load function looks like

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

Which I know is wrong as I have only been taught how to load and replace lists.

You can use "currentLocation" as global variable to change it inside a load-function:

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

If you want to load lists, it depends on how you saved them. A simple possibility is to save each list entry in a new row like this:

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

After that you can read in the list by going line by line and discarding the '\\n' :

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

Another possibility is eg:

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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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