0

I am creating a .txt file to store scores in my snake game. The problem is writing back into the file. my current idea goes somewhat like this:

for line in open("scoreboard.txt", "r+"):
    line = scorelist[y] + namelist[y]

I've already read through the scores, made them into a list, and incorporated a new score, but I can't figure out how to simultaneously cycle through both a line and the lists i'm storing the data in to process, and overwrite the old scores.

1
  • 1
    You don't want to do that. Better to read the file first, make your changes, and then write a new file (the new file can be the same name as your old file). Or you can write to a temporary file, then rename that temporary file to scoreboard.txt. Commented Jun 15, 2014 at 11:04

1 Answer 1

1

You could use JSON encoding to store simple objects into a file:

import json

myscore = [1,2,5]
mynames = ["foo","bar","baz"]

#save
with open("scores.json","w") as f:
    json.dump({'score' : myscore, 'names': mynames},f)

#load
with open("scores.json","r") as f:
    content = json.load(f)
    loadedScore = content['score']
    loadedNames = content['names']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.