0

How to save values in the program, so that it will "remember" them?

martineau
  • 119,623
  • 25
  • 170
  • 301
A.Shah
  • 43
  • 1
  • 1
  • 7

1 Answers1

1

Check out the pickle module.

Here's an example straight from the docs,

import pickle

# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)
gilch
  • 10,813
  • 1
  • 23
  • 28
  • but that's for saving the variable in a different file, isn't it? I want to save the values to a variable in the program – A.Shah Jun 24 '18 at 19:27
  • @A.Shah: It would be very difficult to do that since it would amount to the program modifying it's own code. Although doing that is not impossible, it's somewhat cumbersome, can be difficult to debug, and potentially introduces security issues—i.e. it's a poor programming practice. – martineau Jun 24 '18 at 21:31