Search code examples
pythonstringpython-3.xtuplesstringio

retrieving string from file in python and changing tuples


I have a serious snag in my programming, and it might be an easy fix, but anytime I find something that looks like the right forum post, it's not quite right.

I'm using a file to store data created from one part of my program, like a high score, number of times played, and player name.

I store all this data just fine in the file with a tuple set of ("string key", key's value). I like the ease of retrieval with the dict() command, and have worked with both, but I have to convert the entire data set into a string in order to store it to the file.

And

When I retrieve the data for the next time I open the program, I can't seem to add to the "number of times played" or change the players name for the high score..

It looks a little like this:

import sys
import random
import pickle
save=open ("(path to file)/newgame.txt", 'r+')
save.seek(0)
hiscore=(save.readlines())
def Savedata():
    global save
    global name
    global highscore
    global numplays
#this is where the ideal code would split, modify, and repack the data from the file    
    save.seek(0)
    save.write(str (hiscore))
print (save)
save.seek(0)
save.close()

Can anyone give me any direction add to what I should look into.. I'm on my phone and can't give proper code examples right now...


Solution

  • Have you considered using an actual serializing library? For example json is very useful. Particularly if you're just dumping a dict.

    For example:

    >>> d = {'level':2, 'position':[2,3]}
    >>> import json
    >>> json.dumps(d) # or json.dump(d, save) in your code
    '{"position": [2, 3], "level": 2}'
    

    That way you could simply load the string using json.loads. Or directly a file using json.load.