0

What is the preferred way to store application-specific parameters (persistent data) for my Python program?

I'm creating a Python program, which needs to store some parameters: "project_name", "start_year", "max_value", ...

I don't know which is the best way to store these data (I must reuse them when making calculations and reports): using local TXT files, using a tiny-very-simple DB (does it exist in Python? shall I use SQLite?), ...

Thank you very much in advance.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
SonOfabox
  • 109
  • 3
  • 6

4 Answers4

0

SQLite. Very easy to setup, and you gain a number of builtin db functions. You also won't have to handle file read/writes and parsing.

nathancahill
  • 10,452
  • 9
  • 51
  • 91
0

pickle it:

import pickle

options = {
  'project_name': 'foo',
  'start_year': 2000
}

with open('config.pickle', 'wb') as config:
  pickle.dump(options, config)

The pickle module lets you dump most Python objects into a file and read them back again.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • Hi Blender. Thank you very much for your answer. If I want to store the parameters at different moments of my program, can I use...options = { [code] 'project_name': 'foo', 'start_year': 2000 } options = { 'project_name': 'foo', 'start_year': 2000 } [/code] ? – SonOfabox Jun 03 '12 at 14:05
0

You can use shelve library. From shelve documentation:

A "shelf" is a persistent, dictionary-like object. The difference with dbm databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects -- anything that the "pickle" module can handle

import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of the data at key (raise
                # KeyError if no such key) -- NOTE that this
                # access returns a *copy* of the entry!
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = d.has_key(key)   # true if the key exists; same as "key in d"
list = d.keys() # a list of all existing keys (slow!)
d.close()
0

if scheme is fixed, sqldb is best choise, like sqlite3, plus memcached as cache. if relationship change often, i think flexible data may be stored in files(hash indexed).

whi
  • 2,685
  • 6
  • 33
  • 40