-1

I'm new to python so this is most likely basic knowledge, but how do I read a number from a text file and use it as a variable? I'm trying to make a game where it counts your points and saves it to a plain text file, and when you first run the game it checks for that file and reads the points from your last session. I tried this but it didnt work:

for saving:

    def save():
        with open('gameSave.txt', 'w') as f:
            for points in points:
                f.write('%d' % points)

for loading:

with open("gameSave.txt", "r", encoding="utf-8") as g:
   points = g.readlines()

can anyone help? The points just need to be loaded and save as an integer but i can't figure out how.

Boranbruh
  • 45
  • 3

2 Answers2

0

Write two discrete functions. One to save accumulated points and the other to retrieve what may have previously been saved. Something like this:

FILENAME = 'gameSave.txt'

def getSavedPoints():
    try:
        with open(FILENAME) as data:
            return int(data.read())
    except FileNotFoundError:
        return 0

def savePoints(points):
    with open(FILENAME, 'w') as data:
        data.write(str(points))

points = getSavedPoints()

# play game and accumulate points

points += 100

savePoints(points)

print(getSavedPoints())

So let's assume that no points have previously been saved then the output from this would be:

100
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
-2

Store one number only

points = 200

# Store points
f = open("points.txt", "w")
f.write(str(points))
f.close()

# Retrieve them now
f = open("points.txt", "r")
points = int(f.read())

Cheers

l -_- l
  • 618
  • 4
  • 15