Python Forum

Full Version: Save/Loading using pickle
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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}
please can you point out what each line of code does? sorry quite new and am a bit confused
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?
(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