Store a variable permanently
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Mar 1 21:29:54 EST 2013
On Fri, 01 Mar 2013 11:19:22 +0100, Jean-Michel Pichavant wrote:
> ----- Original Message -----
>> So i have a variable called funds that i want to store the value of
>> even after the program is exited. My funds variable holds the total
>> value of funds i have. I add a certain number of funds each time i run
>> the program by entering how much i want to add. How would i store the
>> funds variable to keep its value? --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
> Hi,
>
> I would serialize the data.
>
> http://docs.python.org/2/library/pickle.html
I don't think we should recommend to a newbie that they use pickle
without even warning them that using pickle is insecure and dangerous if
they are opening pickles from untrusted sources.
But for a single int, pickle too is overkill, and a simple human-readable
and writable file is probably all that is needed:
def save_value(n, configfile='myconfig'):
if n != int(n):
raise ValueError('expected an int')
with open(configfile, 'w') as f:
f.write("value=%d" % n)
def load_value(configfile='myconfig'):
with open(configfile) as f:
s = f.read().strip()
a, b = s.split("=", 1)
if a.strip() != "value":
raise ValueError('invalid config file')
return int(b)
Untested but ought to work.
--
Steven
More information about the Python-list
mailing list