Best way to store config or preferences in a multi-platform way.

Nick Craig-Wood nick at craig-wood.com
Thu May 1 09:30:03 EDT 2008


Lance Gamet <lance at gamet.com> wrote:
>  This project will store most of its actual data in a shared-database, but 
>  I have a small amount of user specific data that I need to be stored like 
>  configuration or preferences for example, the list of databases that the 
>  program should connect to.
> 
>  On Unix this might be a .file, on windows this could be in the registry, 
>  or an ini file or an xml file in ProgramData or AppData or something.
> 
>  Is there a pythony way to store such config data, perhaps there is 
>  already a standard python package for such a purpose?

I've found

  http://docs.python.org/lib/module-ConfigParser.html

To be easy to use and built in.  It makes human readable / editable
.ini - like files.

As for where to store it, I use os.path.expanduser("~") to find the
base directory and a bit of platform specific code.

Something like this snippet

    self.is_windows = sys.platform == 'win32'
    self.home = os.path.expanduser("~")
    if self.is_windows:
        self.config_dir = os.path.join(self.home, "Application Data", self.NAME)
    else:
        self.config_dir = os.path.join(self.home, "."+self.NAME)
    if not os.path.isdir(self.config_dir):
        os.makedirs(self.config_dir, mode=0700)
    self.config_file = os.path.join(self.config_dir, "config")

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list