Python Forum
Save/Loading using pickle - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Save/Loading using pickle (/thread-31006.html)



Save/Loading using pickle - Scordomaniac - Nov-17-2020

So i am trying to make a game using python, and i want to save the amount of coins the player has after they earn coins using pickle, but i have no idea how to do this. let's say i got 10 coins, and i already have 59 coins, i want to write to the file that i have 69 coins, also i want to be able to print the amount of coins the player has when they input 'pls bal' and take the data from the pickle data save thingy and have that.


RE: Save/Loading using pickle - Gribouillis - Nov-17-2020

It is very easy. Here is a way
import pickle

def store(filename, **data):
    with open(filename, 'wb') as ofh:
        pickle.dump(data, ofh)
        
def fetch(filename):
    with open(filename, 'rb') as ifh:
        return pickle.load(ifh)


def main():
    filename = 'foo.pkl'
    store(filename, amount=59)
    data = fetch(filename)
    print(data)
    amount = data['amount']
    amount += 10
    store(filename, amount=amount)
    data = fetch(filename)
    print(data)
    
if __name__ == '__main__':
    main()
Output:
{'amount': 59} {'amount': 69}



RE: Save/Loading using pickle - Scordomaniac - Nov-18-2020

please can you point out what each line of code does? sorry quite new and am a bit confused


RE: Save/Loading using pickle - Gribouillis - Nov-18-2020

Please post the code of the game to see if this applies to your game. The code that I showed stores a number in a file and retrieves that number from the file. Is it not what you want?


RE: Save/Loading using pickle - Scordomaniac - Nov-24-2020

(Nov-18-2020, 08:16 PM)Gribouillis Wrote: Please post the code of the game to see if this applies to your game. The code that I showed stores a number in a file and retrieves that number from the file. Is it not what you want?

it is, i just don't understand what does what in the code