Ask coding questions

← Back to all posts
how to save something
kbadrinath_tcsp (200)

So i'm making a game where the events occur based on the days the user has progressed. however, I have trouble when i'm trying to save the number of days and incrementing it each time. I tried it on my golden survival project and it didn't work. Anybody have an answer? if you want, you can go to my golden survival project, since that has a lot more work done on it.

Commentshotnewtop
dfnk (32)

Pickle is a module in python that can save data locally!

let's start by importing this module, import pickle:

then lest make a variable x = 10.

Now we are going to save this data first make a save.dat file then put this in the python file,

save = open('save.dat', 'wb')
pickle.dump(x, save) # this will dump it into that file
save.close()

this will open the save.dat file in a variable!

then if you go to your save.dat file you will see lots of gibberish, this is because it saves it in a special language!

now to open:

load = open('saver.dat', 'rb')
data = pickle.load(load)
x = data
load.close()

this open the file and then save the data in x, and it will still be a number!
This will save it in a file that when saved will make x stay there!

Bookie0 (2600)

Well you can do like a variable:

days = 1

Then do the code, and at the end of the day,

days += 1

And this adds to the variable days one

kbadrinath_tcsp (200)

yeah i know this, but for some reason it did not work on my last project. @Bookie0

kbadrinath_tcsp (200)

i deleted this day+=1 code on the last project, but you can fork it and try it for yourself. I probably did something wrong on that, so help would be appreciated! the project is golden survival, and it is a pinned repl for me. @Bookie0

Bookie0 (2600)

Wait so where do you want the days to go up? Like when is a new day supposed to start? @kbadrinath_tcsp

kbadrinath_tcsp (200)

If they live through an event. if you go through the functions, you can see when they live, and when they die. @Bookie0

Bookie0 (2600)

Hey, so i forked your repl and did the changes, but there is in inconsistent use of tabs and spaces, i think you used spaces and i used tabs.so i didn’t get to test. It because everything was inconsistent(because it was taking too much time) but i think what you have to do is write global day at each function, and then put day += 1 when you want it. Also, print day after you write that so you can see if its working. Good luck! And hope it works! @kbadrinath_tcsp

SushiPython (43)

I reccomend using something like MongoDB to store your data.

kbadrinath_tcsp (200)

do you know where i can find some help on this? @SushiPython

SushiPython (43)

@kbadrinath_tcsp PyMongo Docs https://pymongo.readthedocs.io/en/stable/ This will also save when the user restarts the repl, as it is a DB.